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_patroniss_com/application/controllers/Increment_approval_bk22jun21.php
<?php if ( ! defined('BASEPATH')) exit('No direct script is allowed');
require_once("Action_controller.php");
class Increment_approval  extends Action_controller{	
	public function __construct(){
		parent::__construct('increment_approval');
		$this->collect_base_info();
		$this->load->model('Process_payroll_model');		
		$this->load->model('Hr_methods_model');
	}
	
	// LOAD PAGE QUICK LINK,FILTERS AND TABLE HEADERS
	public function index(){
		$data['quick_link']    = $this->quick_link;
		$data['table_head']    = $this->table_head;
		$data['master_pick']   = $this->master_pick;
		$data['fliter_list']   = $this->fliter_list;
		$this->load->view("$this->control_name/manage",$data);
	}
	
	//LOAD TABEL WITH FILTERS
	public function search(){
		$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);
		
		//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_id'];
			$label_name       = $fliter['label_name'];
			$field_isdefault  = (int)$fliter['field_isdefault'];
			$array_list       = $fliter['array_list'];
			$field_type       = (int)$fliter['field_type'];			
			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 === 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->form_info 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->master_pick[$label_id], 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);		
		$search_total       = $this->db->query($count_all_query);
		$search_total_info  = $search_total->result();
		$total_count        = $search_total_info[0]->allcount;
		
		$count_query        = str_replace("@SELECT@","count(*) as allcount",$this->base_query);
		$count_query       .= " where $this->prime_table.trans_status = 1 $role_condition $fliter_query $common_search";
		$search_count       = $this->db->query($count_query);
		$search_info        = $search_count->result();
		$filtered_count     = $search_info[0]->allcount;
		
		$search_query      .= " where $this->prime_table.trans_status = 1 $role_condition $fliter_query $common_search";
		$search_query      .= " ORDER BY  $order_col $order_sor";
		if((int)$per_page !== -1){
			$search_query  .= " LIMIT  $start,$per_page";
		}		
		$search_data        = $this->db->query($search_query);
		$search_result      = $search_data->result();
		$num_rows           = $search_data->num_rows();

		//echo "search_query :: \n$search_query\n";		
		echo json_encode(array("draw" => intval($draw),"recordsTotal" => $num_rows,"recordsFiltered" => $filtered_count,"data" => $search_result));		
	}
	
	//LOAD MODEL PAGE VIEW WITH DATA
	public function view($form_view_id=-1){
		//VIEW, FORM INPUT
		$data['view_info']      = $this->view_info;
		$data['form_info']      = $this->form_info;
		
		//VIEW DATA
		$base_query  = str_replace("@SELECT@",$this->view_select,$this->base_query);
		$view_query  = $base_query ." where $this->prime_table.$this->prime_id = $form_view_id and $this->prime_table.trans_status = 1";
		$view_data   = $this->db->query("CALL sp_a_run ('SELECT','$view_query')");
		$view_result = $view_data->result();
		$view_data->next_result();
		$data['form_view']   = $view_result[0];	
		//AUTO COMPLTE,PICK LIST AND CONDITION
		foreach($this->form_info as $from){
			$prime_form_id      = (int)$from->prime_form_id;
			$field_type         = (int)$from->field_type;
			$pick_table         = $from->pick_table;
			$auto_prime_id      = $from->auto_prime_id;
			$auto_dispaly_value = $from->auto_dispaly_value;
			$label_id           = $from->label_name;
			if($field_type === 9){
				if($view_result[0]){
					$get_value = $view_result[0]->$label_id;
					if($get_value){
						$pick_query = 'select '.$auto_dispaly_value.' from '.$pick_table.' where '.$auto_prime_id.' = "'.$get_value.'" and trans_status = 1';
						$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
						$pick_result = $pick_data->result();
						$pick_data->next_result();
						$this->all_pick[$prime_form_id] = $pick_result[0]->$auto_dispaly_value;
					}					
				}
			}
		}
		$data['all_pick']       = $this->all_pick;
		$data['condition_list'] = $this->condition_list;
		
		$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_data   = $this->db->query("CALL sp_a_run ('SELECT','$view_qry')");
		$view_result = $view_data->result();
		$view_data->next_result();
		$row_view_list = array();
		foreach($view_result 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;

		$role_based_query  = 'SELECT * FROM cw_role_base_condition WHERE  role_module_id = "'.$this->control_name.'" and FIND_IN_SET("'.$this->logged_user_role.'",role_condition_for) and trans_status = 1';
		$role_based_info   = $this->db->query("CALL sp_a_run ('SELECT','$role_based_query')");
		$role_based_result = $role_based_info->result();
		$role_based_info->next_result();

		$role_based_condition = array();
		foreach ($role_based_result as $key => $condition) {
			$role_based_condition[$condition->user_condition_type] = $condition->input_columns;
		}
		$data['role_based_condition'] = $role_based_condition;		
		$this->load->view("$this->control_name/form",$data);
	}
	
	//SAVE MODEL DATA TO DATA BASE
	public function save(){
		$unq_chk         = array();
		$prime_qry_key   = "";
		$prime_qry_value = "";
		$prime_upd_query = "";
		$form_id         = (int)$this->input->post($this->prime_id);
		$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;			
			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){
				$value = date('Y-m-d',strtotime($value));
			}else
			if((int)$field_type === 13){
				$value = date('Y-m-d H:i:s',strtotime($value));
			}else
			if((int)$field_type === 8){//textbox only
				$value = str_replace('"',"xdbquot",$value);
				$value = str_replace("'","xquot",$value);
				$value = str_replace("&","xxamp",$value);
			}
					
			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,);
					}
				}
				$form_post_data[$label_id] = $value;
			}
		}

		//Check Exist

		$managers_code_id    = $form_post_data['manager'];
		$manage_qry = 'SELECT company_email_id from cw_employees where employee_code = "'.$managers_code_id.'" and trans_status = 1';
		$manage_info   = $this->db->query("CALL sp_a_run ('SELECT','$manage_qry')"); 
		$manage_result = $manage_info->result();
		$manage_info->next_result();
		$manager_code = $manage_result[0]->company_email_id;

		$apply_month     = $this->input->post('apply_month');
		$approval_type   = $this->input->post('approval_type');
		$employee_code   = $this->input->post('employees');
		$hr_status       = $this->input->post('hr_status');
		$exist_qry = 'SELECT count(*) as count from cw_increment_approval where apply_month = "'.$apply_month.'" and employees = "'.$employee_code.'" and prime_increment_approval_id != "'.$form_id.'" and trans_status = 1';
		$exist_data   = $this->db->query("CALL sp_a_run ('SELECT','$exist_qry')"); 
		$exist_result = $exist_data->result();
		$exist_data->next_result();
		$exist_rows = $exist_result[0]->count;
		if((int)$exist_rows > 0){
			echo json_encode(array('success' => false, 'message' => "Increment Data Already Exist for this Employee"));
			exit(0);
		}	
		$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;		

				if((int)$approval_type !== 3){
					echo $this->search_increment_data($form_post_data,$insert_id);
					exit(0);
				}else{
					$first_approval  = (int)$this->input->post('first_approval');
					$second_approval = (int)$this->input->post('second_approval');
					$third_approval  = (int)$this->input->post('third_approval');
					$hr_status 	  = (int)$this->input->post('hr_status');
					$employee_code    = $form_post_data['employees'];
					/*$emp_id_qry = 'SELECT prime_employees_id from cw_employees where employee_code = "'.$employee_code.'" and trans_status = 1';
					$emp_id_data   = $this->db->query("CALL sp_a_run ('SELECT','$emp_id_qry')"); 
					$emp_id_result = $emp_id_data->result();
					$emp_id_data->next_result();
					$emply_id = $emp_id_result[0]->prime_employees_id;*/
					
					// $this->send_approvalmail_calls($first_level,$second_level,$hr_status,$emply_id,$manager_code);

					echo json_encode(array('success' => TRUE, 'message' => "Successfully added", 'insert_id' => $insert_id));
				}
			}else{
				$first_approval  = (int)$this->input->post('first_approval');
				$second_approval = (int)$this->input->post('second_approval');
				$third_approval  = (int)$this->input->post('third_approval');
				$promoted        = $this->input->post('promoted_designation');				
				$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 .'"';
				$upd_info = $this->db->query("CALL sp_a_run ('UPDATE','$prime_update_query')");
				$apply_month      = $form_post_data['apply_month'];
				$employee_code    = $form_post_data['employees'];
				$category         = $form_post_data['category'];
				// $mail_res = $this->mail($form_post_data,$employee_code,$form_id,$approval_type,$hr_status);
				/*$emp_id_qry = 'SELECT * from cw_employees where employee_code = "'.$employee_code.'" and trans_status = 1';
				$emp_id_data   = $this->db->query("CALL sp_a_run ('SELECT','$emp_id_qry')"); 
				$emp_id_result = $emp_id_data->result();
				$emp_id_data->next_result();
				$emply_id = (int)$emp_id_result[0]->prime_employees_id;*/
				if((int)$approval_type !== 1){
					if((int)$hr_status === 2 && (int)$promoted > 0){
						echo $this->update_promotion($promoted,$employee_code,$category);					
					}else{
						if($upd_info){
							echo json_encode(array('success' => TRUE, 'message' => "Successfully updated",'insert_id' => $form_id));	
						}else{
							 echo json_encode(array('success' => FALSE, 'message' => "Please try After Sometime..."));
						}						
					}								
				}else{	
					if($upd_info){
						echo json_encode(array('success' => TRUE, 'message' => "Successfully updated",'insert_id' => $form_id));	
					}else{
						 echo json_encode(array('success' => FALSE, 'message' => "Please try After Sometime..."));
					}						
				}					
			}
		}
	}
	public function update_promotion($promoted,$employee_code,$category){
		$emp_data_qry      = 'select prime_employees_id,employee_code,emp_name,designation,role from cw_employees where employee_code = "'.$employee_code.'"';
		$emp_data   = $this->db->query("CALL sp_a_run ('RUN','$emp_data_qry')");
		$emp_result = $emp_data->result();
		$emp_data->next_result();
		$emp_id          = $emp_result[0]->prime_employees_id;
		$emp_name        = $emp_result[0]->emp_name;
		$old_category    = $emp_result[0]->role;
		$old_designation = $emp_result[0]->designation;
		$logged_id       = $this->logged_id;
		$created_on      = date("Y-m-d h:i:s");
		$old_category_val    = $this->master_pick['category'][$old_category];
		$old_designation_val = $this->master_pick['designation'][$old_designation];
		$category_value      = $this->master_pick['category'][$category];
		$promoted_value      = $this->master_pick['designation'][$promoted];

		$prime_qry_key   = "prime_employees_id,employee_code,emp_name,label_name,old_value,new_value,module_name,trans_created_by,trans_created_date";	

		$prime_update_query  = 'UPDATE cw_employees SET role = "'.$category.'",designation = "'.$promoted.'",trans_updated_by = "'.$this->logged_id.'",trans_updated_date = "'.date("Y-m-d h:i:s").'" WHERE employee_code = "'.$employee_code.'"';
		$upd_result = $this->db->query("CALL sp_a_run ('RUN','$prime_update_query')");		

		if($upd_result){
			if($category !== $old_category){
				$category_value = "(\"$emp_id\",\"$employee_code\",\"$emp_name\",\"category\",\"$old_category_val\",\"$category_value\",\" increment_approval \",\"$logged_id\",\"$created_on\")";
				$prime_insert_query = "insert into cw_employees_log ($prime_qry_key) values $category_value";
				$insert_info        = $this->db->query("CALL sp_a_run ('RUN','$prime_insert_query')");
			}
			if($promoted !== $old_designation){
				$designation_value = "(\"$emp_id\",\"$employee_code\",\"$emp_name\",\"designation\",\"$old_designation_val\",\"$promoted_value\",\"increment_approval\",\"$logged_id\",\"$created_on\")";
				$prime_insert_query = "insert into cw_employees_log ($prime_qry_key) values $designation_value";
				$insert_info        = $this->db->query("CALL sp_a_run ('RUN','$prime_insert_query')");
			}
			 echo json_encode(array('success' => TRUE, 'message' => "Promotion Successfully updated",'insert_id' => $form_id));
		}else{
			 echo json_encode(array('success' => FALSE, 'message' => "Please try After Sometime..."));
		}		
	}

	public function view_log($view_id){
		$log_qry        = 'SELECT cw_employees.employee_code as updated,emp_name,column_name,percentage,old_value,new_value,cw_increment_update_log.trans_created_date FROM cw_increment_update_log inner join cw_employees on cw_employees.employee_code = cw_increment_update_log.trans_created_by WHERE prime_increment_app_id ="'.$view_id.'"';
		$log_qry_data   = $this->db->query("CALL sp_a_run ('RUN','$log_qry')");
		$log_qry_result = $log_qry_data->result();
		$log_qry_data->next_result();
		$data['log_qry_result'] = $log_qry_result;
		$this->load->view("$this->control_name/view_log",$data);
	}
	public function view_history($view_id){
		//Get Employee code		
		$emp_qry        = 'SELECT employees FROM cw_increment_approval WHERE prime_increment_approval_id ="'.$view_id.'"';
		$emp_qry_data   = $this->db->query("CALL sp_a_run ('RUN','$emp_qry')");
		$emp_qry_result = $emp_qry_data->result();
		$emp_qry_data->next_result();
		$employee_code = $emp_qry_result[0]->employees;
		//Get History of Hike for this Employee
		$log_qry        = 'SELECT  cw_increment_approval.employees,cw_increment_approval.effective_date,SUM(difference_value) as increment_value,cw_increment_approval.apply_month from cw_increment inner join cw_increment_approval on cw_increment_approval.prime_increment_approval_id = cw_increment.increment_approval_id WHERE cw_increment_approval.employees ="'.$employee_code.'" and hr_status = 2';
		$log_qry_data   = $this->db->query("CALL sp_a_run ('RUN','$log_qry')");
		$log_qry_result = $log_qry_data->result();
		$log_qry_data->next_result();
		$data['log_qry_result'] = $log_qry_result;
		$this->load->view("$this->control_name/view_history",$data);
	}
	//UPDATE STATUS TO DELETE IN MODULE PRIMARY TABLE
	public function delete(){
		$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;
				$select_table            = '';
				$select_label            = '';
				$select_trans_status     = '';
				$select_where            = '';
				foreach($prime_module_id as $check_modules){
					$table_name            = "cw_".$check_modules;
					$table_rename          = $table_name."_$i";
					$select_table         .= "$table_rename.$label_name[$i],";
					$select_label         .= " $table_name $table_rename,";
					if((int)$i === 0){
						$select_trans_status  .= "( $table_rename.trans_status = 1";
						$select_where         .= " and ($table_rename.$label_name[$i] in ($delete_ids)";
					}else{
						$select_trans_status  .= " and $table_rename.trans_status = 1";
						$select_where         .= " or $table_rename.$label_name[$i] in ($delete_ids)";
					}
					$i++;
				}
				$select_trans_status .= ")";
				$select_where        .= ")";
				$select_table         = rtrim($select_table,',');
				$select_label         = rtrim($select_label,',');
				$check_module_query  .= 'SELECT '.$select_table.' from '.$select_label.' WHERE '.$select_trans_status.' '.$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){
					$can_process   = False;
					$delete_status = False;
				}
			}
			if($delete_status){
				$delete_query  = 'DELETE FROM '. $this->prime_table .'  WHERE '. $this->prime_id .' in ('. $delete_ids .')';
				if($this->db->query("CALL sp_a_run ('RUN','$delete_query')")){
					$row_set_query   = 'SELECT form_view_label_name from cw_form_view_setting where form_view_type = "3" and prime_view_module_id = "'. $this->control_name .'" and trans_status = 1';
					$row_set_info    = $this->db->query("CALL sp_a_run ('SELECT','$row_set_query')");
					$row_count       = (int)$row_set_info->num_rows();
					$row_set_info->next_result();
					if($row_count !== 0){
						$row_set_result         = $row_set_info->result();
						$delete_table_name      = '';
						$delete_table_condition = '';
						foreach($row_set_result as $row_set){
							$row_set_table_name      = "cw_".$this->control_name."_".$row_set->form_view_label_name;
							$delete_table_name      .= "$row_set_table_name,";
							$delete_table_condition .= " $row_set_table_name.$this->prime_id  in ('$delete_ids') and";
						}
						$delete_table_name           = rtrim($delete_table_name,',');
						$delete_table_condition      = rtrim($delete_table_condition,'and');
						$delete_row_set_query  = 'DELETE FROM '. $delete_table_name .'  WHERE '. $delete_table_condition.'';
						$this->db->query("CALL sp_a_run ('RUN','$delete_row_set_query')");						
					}
					$can_process = False;
				}
				
			}
		}
		if($can_process){
			$created_on = date("Y-m-d h:i:s");
			$prime_upd_query    .= 'trans_deleted_by = "'. $this->logged_id .'",trans_deleted_date = "'.$created_on.'"';
			$prime_update_query  = 'UPDATE '. $this->prime_table .' SET trans_status = 0,'. $prime_upd_query .' WHERE '. $this->prime_id .' in ('. $delete_ids .')';
			if($this->db->query("CALL sp_a_run ('UPDATE','$prime_update_query')")){
				echo json_encode(array('success' => TRUE, 'message' => "Successfully Deleted"));
			}else{
				echo json_encode(array('success' => FALSE, 'message' => "Unable to delete"));
			}
		}else
		if($delete_status){
			echo json_encode(array('success' => TRUE, 'message' => "Successfully Deleted"));
		}else{
			$modules = ucwords($check_table_rlst->prime_module_id);
			echo json_encode(array('success' => FALSE, 'message' => "Unable to delete, This value is already used in $modules 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(){
		$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"));
		}
	}
	public function rowset_remove_file(){
		$table_name  = $this->input->post('table_name_set');
		$row_id     = (int)$this->input->post('row_id');
		$input_name     = $this->input->post('input_name');
		$view_id     = (int)$this->input->post('view_id');
		$primes_id     = (int)$this->input->post('primes_id');
		$remove_cw = str_replace("cw_","",$table_name);
		$primary_id = "prime_".$remove_cw."_id";
		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 '.$primary_id.' = "'. $row_id .'"';
			$this->db->query("CALL sp_a_run ('UPDATE','$update_query')");
			$row_set_edit = $this->get_row_set_data($view_id,$primes_id);
			$div_id = $row_set_edit['div_id'];
			$table_id = $row_set_edit['table_id'];
			$row_set_view = $row_set_edit['row_set_view'];
			echo json_encode(array('success' => TRUE, 'message' => "Successfully updated",'div_id' => $div_id, 'table_id' => $table_id,'row_set_view'=>$row_set_view));
		}else{
			echo json_encode(array('success' => FALSE, 'message' => "Unable to process your request"));
		}
	}
	
	//IMPORT FILE VIEW INFORMATION
	public function import(){
		$data['module_id']     = $this->control_name;		
		$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);
	}
	/* Increment Custom Code START */
	public function get_employee_list(){
		$category = $this->input->post('category');
		$emp_query  = 'SELECT employee_code,emp_name FROM cw_employees WHERE role = "'.$category.'" and trans_status = 1 and termination_status = 0';
		$emp_info   = $this->db->query("CALL sp_a_run ('SELECT','$emp_query')");
		$emp_result = $emp_info->result();
		$emp_info->next_result();
		$emp_list = "<option value=''>---- Select Employee ----</option>";
		foreach($emp_result as $result){
			$id        = $result->employee_code;
			$name      = ucwords($result->emp_name);
			$emp_code  = $result->employee_code;
			$emp_list .= "<option value='$id'>$emp_code - $name</option>";
		}
		echo $emp_list;
	}
	//Check Payroll is processed
	public function check_payroll_process(){
		$month     = $this->input->post('apply_month');
		$category  = $this->input->post('category');
		$employee  = $this->input->post('employee');		
		$from      = $this->input->post('from');
		$employee_qry    = 'select role from cw_employees where cw_employees.employee_code ="'.$employee.'"';
		$employee_data   = $this->db->query("CALL sp_a_run ('SELECT','$employee_qry')");
		$employee_result = $employee_data->result();
		$employee_data->next_result();
		$category  = $employee_result[0]->role;
		if($from === "apply_month"){
			$payroll_qry = 'SELECT * from cw_transactions where transactions_month = "'.$month.'" and role = "'.$category.'" and employee_code = "'.$employee.'" and trans_status = 1';
			$payroll_data   = $this->db->query("CALL sp_a_run ('SELECT','$payroll_qry')");
			$payroll_result = $payroll_data->result();
			$payroll_data->next_result();
			$num_rows     = $payroll_data->num_rows();
			if((int)$num_rows >= 1){
				echo json_encode(array('success' => true, 'message' => "Payroll Processed For this Month"));
			}else{
				echo json_encode(array('success' => false));
			}	
		}else
		if($from === "effective_date"){
			$effective_date  = $this->input->post('effective_date');
			//Salary 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 ="'.$category.'"';
			$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();	
			//Get Salary Start Date		
			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){
					$sal_start = $day_start;
					//For Current month between days increment
					$date = new DateTime("01-$month 00:00:00");
					$date->modify('-1 month');
					$salary_start_date = $date->format("Y-m-$sal_start");	
					$salary_end_date   = date("Y-m-d",strtotime($day_end."-".$month));
				}else{
					$sal_start = '01';
					$date = new DateTime("01-$month 00:00:00");
					$salary_start_date = $date->format("Y-m-$sal_start");	
					$salary_end_date   = date("Y-m-d",strtotime($day_end."-".$month));
				}
			}
			if(strtotime($effective_date) >= strtotime($salary_end_date)){
				echo json_encode(array('success' => true, 'message' => "Future Effective Date Not Allowed"));
			}else{
				echo json_encode(array('success' => false));
			}
		}		
	}
	public function get_lop_days(){
		$category         = $this->input->post('category');
		$employee         = $this->input->post('employee');
		$process_by       = $this->input->post('process_by');
		$apply_month      = $this->input->post('apply_month');
		if((int)$process_by === 1){
			$days_column = "lop_days";
		}else{
			$days_column = "paid_days";
		}
		$effective_date   = date("Y-m-d",strtotime($this->input->post('effective_date')));
		$eff_date         = date("d",strtotime($this->input->post('effective_date')));		
		$salary_dates     = $this->Process_payroll_model->get_salary_date($category);
		$day_start        = $salary_dates['day_start'];
		$day_end          = $salary_dates['day_end'];
		$day_conditions   = $salary_dates['day_conditions'];
		if((int)$day_conditions === 3 && $eff_date >= $day_start){
			$effective_month = date("m-Y", strtotime("+1 month", strtotime($this->input->post('effective_date'))));				
		}else{
			$effective_month  = date("m-Y",strtotime($this->input->post('effective_date')));
		}
		//Payroll Process Check AS Discussed with Radhika Mam on 03Sep2020 Removed this condition
		/*$trans_check_qry = 'select * from cw_monthly_input where employee_code= "'.$employee.'" and trans_status=1 and process_month = "'.$effective_month.'"';
		$trans_check_data   = $this->db->query("CALL sp_a_run ('SELECT','$trans_check_qry')");
		$trans_check_result = $trans_check_data->result();
		$trans_check_data->next_result();
		$trans_rslt_count = $trans_check_data->num_rows();	*/	

		//Date Of Joining Check
		$doj_check_qry = 'select count(*) as rslt_count from cw_employees where employee_code= "'.$employee.'" and trans_status=1 and date_of_joining <="'.$effective_date.'"';
		$doj_check_data   = $this->db->query("CALL sp_a_run ('SELECT','$doj_check_qry')");
		$doj_check_result = $doj_check_data->result();
		$doj_check_data->next_result();
		$rslt_count = $doj_check_result[0]->rslt_count;
		
		//Dynamic column list array
		$get_column_qry = 'select db_column from cw_payroll_function_map where map_statutory_name= 12 and loc_name = "'.$days_column.'" and trans_status=1';
		$get_column_data   = $this->db->query("CALL sp_a_run ('SELECT','$get_column_qry')");
		$get_column_result = $get_column_data->result();
		$get_column_data->next_result();
		$lop_days_db = $get_column_result[0]->db_column;
		if(!$lop_days_db){
			echo json_encode(array('success' => false, 'message' => "Lop Days / Paid Days Not Mapped in function column mapping in employee module"));
			exit(0);
		}
		$lop_qry = 'SELECT '.$lop_days_db.' from cw_transactions where process_month = "'.$effective_month.'" and employee_code = "'.$employee.'" and trans_status = 1';
		$lop_data   = $this->db->query("CALL sp_a_run ('SELECT','$lop_qry')");
		$lop_result = $lop_data->result();
		$lop_data->next_result();
		$lop_days = $lop_result[0]->$lop_days_db;
		if(empty($lop_result)){
			$lop_days = 0;
		}		
		//if((int)$trans_rslt_count > 0){ AS Discussed with Radhika Mam on 03Sep2020 Removed this condition
			if((int)$rslt_count === 1 ){
				echo json_encode(array('success' => true, 'lop_days' => $lop_days));
			}else{
				echo json_encode(array('success' => false, 'message' => "Date of joining not greater than effective date "));
			}
		/*}else{
			echo json_encode(array('success' => false, 'message' => "Month Input Not Processed for this Employee"));
		}	*/	
	}
		//LOAD PAGE TABLE VIEW WITH DATA BASED ON SEARCH FILTERS
	public function search_increment_data($form_post_data,$form_id){
		$effective_date   = date("Y-m-d",strtotime($form_post_data['effective_date']));
		$apply_month      = $form_post_data['apply_month'];
		$employee_code    = $form_post_data['employees'];
		$category         = $form_post_data['category'];
		$before_days      = $form_post_data['before'];
		$after_day        = $form_post_data['after'];	
		$category         = $form_post_data['category'];	
		$process_by       = $form_post_data['process_by'];	

		$employee_qry    = 'select role from cw_employees where cw_employees.employee_code ="'.$employee_code.'"';
		$employee_data   = $this->db->query("CALL sp_a_run ('SELECT','$employee_qry')");
		$employee_result = $employee_data->result();
		$employee_data->next_result();
		$category  = $employee_result[0]->role;	

		if($category){
			$inc_column_qry = 'select GROUP_CONCAT(label_name) as label_names from cw_form_setting where prime_module_id = "employees" and increment_check = 1 and trans_status = 1';
			$inc_column_data   = $this->db->query("CALL sp_a_run ('SELECT','$inc_column_qry')");
			$inc_column_result = $inc_column_data->result();
			$inc_column_data->next_result();	
			if(!$inc_column_result[0]->label_names){
				echo json_encode(array('success' => false, 'message' => "Increment Columns Not Created"));
				exit(0);
			}
			//GET Values
			$value_qry    = 'SELECT '.$inc_column_result[0]->label_names.' from cw_employees where employee_code = "'.$employee_code.'" and trans_status = 1';
			$value_data   = $this->db->query("CALL sp_a_run ('SELECT','$value_qry')");
			$value_result = $value_data->result();
			$value_data->next_result();
			if($value_result){
				foreach($value_result[0] as $column_name => $value){			
					$current_value = $value;
					$new_value     = $value;
					$diff_value    = $new_value - $current_value;
					$exist_qry = 'SELECT count(*) as count from cw_increment where apply_on = "'.$apply_month.'" and employee_code = "'.$employee_code.'" and column_name = "'.$column_name.'" and increment_approval_id =  "'.$form_id.'" and trans_status = 1';
					$exist_data   = $this->db->query("CALL sp_a_run ('SELECT','$exist_qry')"); 
					$exist_result = $exist_data->result();
					$exist_data->next_result();
					$exist_rows = $exist_result[0]->count;	
					if((int)$exist_rows === 0){
						$insert_query = 'INSERT into cw_increment (increment_approval_id,apply_on,category,employee_code,effective_date,process_by,before_day,after_day,column_name,current_value,new_value,difference_value,trans_created_by,trans_created_date) values ("'.$form_id.'","'.$apply_month.'","'.$category.'","'.$employee_code.'","'.$effective_date.'","'.$process_by.'","'.$before_days.'","'.$after_day.'","'.$column_name.'","'.$current_value.'","'.$new_value.'","'.$diff_value.'","'.$this->logged_id.'","'.date('Y-m-d H:i:s').'")';
						$insert_info        = $this->db->query("CALL sp_a_run ('INSERT','$insert_query')");
						$insert_result      = $insert_info->result();
						$insert_info->next_result();	
					}else{
						$update_query   = 'UPDATE cw_increment SET effective_date = "'. $effective_date .'",process_by = "'. $process_by .'",before_day = "'. $before_days .'",after_day = "'. $after_day .'",new_value = "'. $new_value .'",difference_value = "'. $diff_value .'",trans_updated_by = "'. $this->logged_id .'",trans_updated_date = "'. $created_on .'" WHERE employee_code = "'. $employee_code .'" and apply_on = "'.$apply_month.'" and column_name = "'.$column_name.'"';
					$update_result = $this->db->query("CALL sp_a_run ('UPDATE','$update_query')");
					}				
				}
			}else{
				echo json_encode(array('success' => false, 'message' => "Increment Columns Not Mapped"));
				exit(0);
			}			
			return $this->get_increment_data($category,$apply_month,$employee_code,$form_id);
		}else{
			echo json_encode(array('total'=>0,'rows'=>0));
		}
	}

	public function check_has_formula($column){
		$input_query = 'SELECT * FROM cw_form_bind_input 
			INNER JOIN cw_form_condition_formula ON cw_form_condition_formula.prime_cond_id = cw_form_bind_input.input_cond_id 
		WHERE input_cond_module_id ="employees" AND cond_drop_down ="role" AND line_input_bind_to ="'.$column.'" AND cw_form_condition_formula.trans_status=1';
		$input_data   = $this->db->query("CALL sp_a_run ('SELECT','$input_query')");
		$input_result = $input_data->result();
		$input_data->next_result();
		$num_rows = $input_data->num_rows();
		return $num_rows;
	}
	public function get_increment_data($category,$apply_month,$employee_code,$form_id){
		
		//Get DB Columns
		$mapping_data   = $this->Hr_methods_model->get_mapped_db_column(12);
		$fixed_basic_db = $mapping_data['fixed_basic'];
		$hr_sts_qry = 'SELECT count(*) as count from cw_increment_approval where apply_month = "'.$apply_month.'" and employees = "'.$employee_code.'" and trans_status = 1 and approve_status in(2,3)';		
		$hr_sts_data   = $this->db->query("CALL sp_a_run ('SELECT','$hr_sts_qry')");
		$hr_sts_result = $hr_sts_data->result();		
		$hr_sts_data->next_result();
		$status = $hr_sts_result[0]->count;	
		/*$first_approval_qry = 'SELECT count(*) as count from cw_increment_approval where apply_month = "'.$apply_month.'" and employees = "'.$employee_code.'" and trans_status = 1 and approve = 2';		
		$first_approval_data   = $this->db->query("CALL sp_a_run ('SELECT','$first_approval_qry')");
		$first_approval_result = $first_approval_data->result();		
		$first_approval_data->next_result();
		$first_approve_status  = $first_approval_result[0]->count;		*/

		$list_qry = 'SELECT prime_increment_id,column_name,current_value,difference_value,new_value,employee_code,apply_on,view_name,effective_date,after_day,process_by,percentage,increment_approval_id from cw_increment inner join cw_form_setting on cw_form_setting.label_name = cw_increment.column_name where apply_on = "'.$apply_month.'" and employee_code = "'.$employee_code.'" and cw_increment.trans_status = 1 group by label_name';		
		$list_data   = $this->db->query("CALL sp_a_run ('SELECT','$list_qry')");
		$list_result = $list_data->result();		
		$list_data->next_result();

		$num_rows     = $list_data->num_rows();
		$tr_line = "";
		$arrear_gross = 0;
		$arrear_basic = 0;
		$btn = "";
		foreach ($list_result as $table_info){
			$diff_value    = $table_info->difference_value;
			$new_value     = $table_info->new_value;
			$arrear_gross  = $arrear_gross + $new_value;
			if($table_info->column_name === $fixed_basic_db){
				$arrear_basic = $new_value;
			}
			$hid_column = "<input type='hidden' name = 'column_name[]' id='column_name' value='$table_info->column_name'/>";
			$diff_hid   = "<input type='hidden' name = 'diff_value[]' id='diff_value' value='$diff_value'/>";
			$current_hid = "<input type='hidden' name = 'current_value[]' id='current_value' value='$table_info->current_value'/>";
			$check_has_formula = $this->check_has_formula($table_info->column_name);
			if((int)$check_has_formula === 0){
				$readonly = "";
			}else{
				$readonly = "readonly";
			}
			/*if((int)$first_approve_status === 0){
				$readonly = "";
			}else{
				$readonly = "readonly";
			}
			if((int)$status === 0){
				$readonly = "";
			}else{
				$readonly = "readonly";
			}*/
			if($table_info->column_name === 'yearly_ctc'){
				$dis = "";
			}else{
				$dis = "style = 'display:none'";
			}
			$perc = "percentage_".$table_info->prime_increment_id;
			
			$tr_line.= "<tr $dis>$current_hid $hid_column $diff_hid<td>$table_info->employee_code</td><td>$table_info->apply_on</td><td>$table_info->view_name</td><td>$table_info->current_value</td><td style='width: 15%;'><input type='text' class='form-control input-sm number' name = 'percentage' id='$perc' onchange=percentage_calc('$new_value',this.value,$category,$table_info->prime_increment_id,'$table_info->current_value','$table_info->employee_code','$table_info->apply_on','$table_info->column_name') value = '$table_info->percentage' $readonly></td><td style='width: 15%;'><input type='text' class='form-control input-sm increment_cal number' name = 'new_value[]' id='$table_info->column_name' onchange=update_table('$new_value',$category,$table_info->prime_increment_id,'$table_info->current_value','$table_info->employee_code','$table_info->apply_on','$table_info->column_name','$table_info->percentage','$table_info->effective_date','$table_info->after_day') value='$table_info->new_value' $readonly></td><td>$diff_value</td></tr>";
			//if((int)$this->logged_user_role === 1){
				$btn = "<a style='display:none;' class='btn btn-primary btn-sm' id='save_increment' onclick=save_increment($category,$table_info->prime_increment_id,'$table_info->employee_code','$table_info->apply_on','$table_info->effective_date','$table_info->after_day','$arrear_basic','$arrear_gross',$table_info->process_by,$table_info->increment_approval_id) >Process Increment</a>";
			//}
			
		}
		///*<th>Percentage</th>*/
		$table_data = "<div class='form-group'>
			$btn
		</div><table id='inc_table' class='table table hover'>
				<thead>
					<tr>
						<th>Employee Code</th>
						<th>Apply Month</th>
						<th>Column Name</th>
						<th>Current Value</th>	
						<th>Hike Percentage</th>						
						<th>New Value</th>
						<th>Differences</th>	
					</tr>
				</thead>
				<tbody>$tr_line</tbody>
		   </table>";
		echo json_encode(array('success'=>true,'insert_id'=>$form_id,'table_data'=>$table_data));
	}
	public function get_increment(){
		$apply_month      = $this->input->post('apply_month');
		$employee_code    = $this->input->post('employee_code');
		//$category         = $this->input->post('category');
		$view_id          = $this->input->post('view_id');
		$employee_qry    = 'select role from cw_employees where cw_employees.employee_code ="'.$employee_code.'"';
		$employee_data   = $this->db->query("CALL sp_a_run ('SELECT','$employee_qry')");
		$employee_result = $employee_data->result();
		$employee_data->next_result();
		$category  = $employee_result[0]->role;	
		$this->get_increment_data($category,$apply_month,$employee_code,$view_id);
	}
	public function update_table(){
		$prime_id         = $this->input->post('prime_id');
		$increment_id     = $this->input->post('increment_id');
		$new_value        = $this->input->post('new_value');
		$diff_value       = $this->input->post('diff_value');
		$apply_month      = $this->input->post('apply_month');
		$employee_code    = $this->input->post('employee_code');
		$category         = $this->input->post('category');
		$percentage       = $this->input->post('percentage');
		$column_name      = $this->input->post('column_name');
		$old_value        = $this->input->post('old_value');
		$created_on       = date("Y-m-d H:i:s");	
		$logged_code      = $this->session->userdata('logged_emp_code');
		/*$first_approval      = (int)$this->input->post('first_approval');
		$second_approval     = (int)$this->input->post('second_approval');
		$third_approval     = (int)$this->input->post('third_approval');
		$hr_status        = (int)$this->input->post('hr_status');*/
		
		//Insert Increment Log
		$insert_query = 'insert into cw_increment_update_log(prime_increment_app_id,apply_on,category,employee_code,column_name,percentage,old_value,new_value,trans_created_by,trans_created_date) value ("'.$prime_id.'","'.$apply_month.'","'.$category.'","'.$employee_code.'","'.$column_name.'","'.$percentage.'","'.$old_value.'","'.$new_value.'","'.$logged_code.'","'.date('Y-m-d H:i:s').'")';
		$insert_result = $this->db->query("CALL sp_a_run ('RUN','$insert_query')");

		$upd_query   = 'UPDATE cw_increment SET new_value = "'. $new_value .'",percentage = "'. $percentage .'",difference_value = "'. $diff_value .'",trans_updated_by = "'. $this->logged_id .'",trans_updated_date = "'. $created_on .'" WHERE prime_increment_id = "'. $increment_id .'"';
		$upd_result = $this->db->query("CALL sp_a_run ('UPDATE','$upd_query')");

		if($upd_result){
			return $this->get_increment_data($category,$apply_month,$employee_code,$prime_id);
		}
		
	}
	public function get_designation_list(){
		$employee_code = $this->input->post('employees');
		$emp_query  = 'SELECT designation,role,approve_type,first_level_approval,second_level_approval,third_level_approval FROM cw_employees WHERE employee_code = "'.$employee_code.'" and trans_status =1';
		$emp_info   = $this->db->query("CALL sp_a_run ('SELECT','$emp_query')");
		$emp_result = $emp_info->result();
		$emp_info->next_result();
		$designation           = $emp_result[0]->designation;
		$category              = $emp_result[0]->role;
		$approve_type          = $emp_result[0]->approve_type;
		$first_level_approval  = $emp_result[0]->first_level_approval;
		$second_level_approval = $emp_result[0]->second_level_approval;
		$third_level_approval  = $emp_result[0]->third_level_approval;
		echo json_encode(array('success'=>true,'designation'=>$designation,'category'=>$category,'increment_approve_type'=>$approve_type,'first_level_approval'=>$first_level_approval,'second_level_approval'=>$second_level_approval,'third_level_approval'=>$third_level_approval));
	}
	//Calculate Arrear values and store database
	public function save_increment(){
		$trans_array=array();
		$prime_id         = $this->input->post('prime_id');
		$inc_approval_id  = $this->input->post('increment_approval_id');
		$new_array        = $this->input->post('new_value');
		$current_array    = $this->input->post('current_value');
		$diff_array       = $this->input->post('diff_value');
		$employee_code    = $this->input->post('employee_code');
		$apply_month      = $this->input->post('apply_on');
		$trans_column     = $this->input->post('column_name');
		$effective_date   = $this->input->post('effective_date');
		$after_day        = $this->input->post('after_day');
		$category         = $this->input->post('category');
		$process_by       = $this->input->post('process_by');
		$created_on       = date("Y-m-d h:i:s");
		$effective        = $this->input->post('effective_date'); //used for insert
		//Employee Data 
		$emp_qry        = 'SELECT metro FROM `cw_employees` WHERE employee_code ="'.$employee_code.'"';
		$emp_qry_data   = $this->db->query("CALL sp_a_run ('RUN','$emp_qry')");
		$emp_qry_result = $emp_qry_data->result();
		$emp_qry_data->next_result();
		$metro          = $emp_qry_result->metro;



		$first_approval  = (int)$this->input->post('first_approval');
		$second_approval = (int)$this->input->post('second_approval');
		$third_approval = (int)$this->input->post('third_approval');
		$hr_status 	  = (int)$this->input->post('hr_status');
		// $employee_code    = $form_post_data['employees'];
		$emp_id_qry = 'SELECT * from cw_employees where employee_code = "'.$employee_code.'" and trans_status = 1';
		$emp_id_data   = $this->db->query("CALL sp_a_run ('SELECT','$emp_id_qry')"); 
		$emp_id_result = $emp_id_data->result();
		$emp_id_data->next_result();
		$emply_id = $emp_id_result[0]->prime_employees_id;
		// $this->send_approvalmail_calls($first_approval,$second_approval,$hr_status,$emply_id,$manager_code);
		$formula_exist_qry    = 'SELECT count(*) as count FROM `cw_form_bind_input` 
            INNER JOIN `cw_form_condition_formula` ON cw_form_condition_formula.prime_cond_id = cw_form_bind_input.input_cond_id 
        WHERE input_cond_module_id ="employees" AND line_input_bind_col !="" AND cw_form_condition_formula.trans_status=1 and cond_order != 0';
		$formula_exist_data   = $this->db->query("CALL sp_a_run ('RUN','$formula_exist_qry')");
		$formula_exist_result = $formula_exist_data->result();
		$formula_exist_data->next_result();
		$formula_exist        = $formula_exist_result[0]->count;
		if((int)$formula_exist > 0){
			$trans_array         = $this->input->post('arr_for');	
			$trans_array['metro'] = $metro;
			$new_array           = $this->increment_formula($trans_array);
		}

		// Arrear Insert Data
		$apply_date = date("d",strtotime($effective_date))."-".$apply_month;
		$date = strtotime($apply_date); 
		$apply_date = date('Y-m-d', $date); 			
		$arrear_value          = 0;
		$cumulate_arrear_value = 0;
		$arrear_pf             = 0;
		$cumulate_arrear_pf    = 0;			
		//Developer Understanding	
		/*$loc_column_list = array("earned_gross"=>"Earned Gross","paid_days"=>"Paid Days","month_days"=>"Month Days","fixed_basic"=>"Fixed Basic","fixed_gross"=>"Fixed Gross","professional_tax_amount"=>"Professional Tax","esi_loc"=>"ESI Location","esi_elig"=>"ESI Eligibility","arrear_gross"=>"Arrear Gross","arrear_pf_gross"=>"Arrear PF Gross");*/	
		$mapping_data       = $this->Hr_methods_model->get_mapped_db_column(12);
		$paid_days_db       = $mapping_data['paid_days'];
		$month_days_db      = $mapping_data['month_days'];
		$fixed_basic_db     = $mapping_data['fixed_basic'];
		$earned_basic_db    = $mapping_data['earned_basic'];
		$earned_gross_db    = $mapping_data['earned_gross'];
		$arrear_gross_db    = $mapping_data['arrear_gross'];
		$arrear_pf_gross_db = $mapping_data['arrear_pf_gross'];

		//Arrear PF Gross Formula
		$get_arrear_pf_gross_qry = 'select payroll_formula from cw_payroll_formula where formula_for = "'.$category.'" and out_column = "'.$arrear_pf_gross_db.'"  and trans_status =1';
		$arrear_pf_gross_data   = $this->db->query("CALL sp_a_run ('SELECT','$get_arrear_pf_gross_qry')");
		$arrear_pf_gross_result = $arrear_pf_gross_data->result();
		$arrear_pf_gross_data->next_result();		
		$arrear_pf_gross_formula    = $arrear_pf_gross_result[0]->payroll_formula;		

		//Get Transaction Columns
		$get_trans_colums  = 'SELECT GROUP_CONCAT(label_name) as label_name FROM cw_form_setting where arrear_pf_check = 1';		
		$trans_colums_data   = $this->db->query("CALL sp_a_run ('SELECT','$get_trans_colums')");
		$trans_colums_result = $trans_colums_data->result();
		$trans_colums_data->next_result();
		$trans_columns = explode(",",$trans_colums_result = $trans_colums_result[0]->label_name);		
		if($arrear_pf_gross_formula){
			if(!$trans_colums_result){
				echo json_encode(array('success' => false, 'message' => "Arrear PF Columns Not Mapped"));
				exit(0);
			}
		}			
		//Get Last Month			
		$eff_date_format = date("Y-m-d",strtotime($effective_date));
		$datestring= "$eff_date_format first day of last month";
		$dt=date_create($datestring);
		$prev_month = $dt->format('Y-m');	
		$eff_date  = date("d",strtotime($effective_date));
		$eff_month = date("m-Y",strtotime($effective_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 ="'.$category.'"';
		$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();	
		//Get Salary Start Date		
		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){
				$sal_start = $day_start;
				/*if($eff_date >= $sal_start){
					$date_next_month = "$eff_date_format first day of next month";
					$dt_next_month=date_create($date_next_month);
					$next_month = $dt_next_month->format('Y-m');
					//$effective_date = $next_month."-".$eff_date;					
				}*/
				//For Current month between days increment
				$date = new DateTime("01-$apply_month 00:00:00");
				$date->modify('-1 month');
				$salary_start_date = $date->format("Y-m-$sal_start");	
				$salary_end_date   = date("Y-m-d",strtotime($day_end."-".$apply_month));	
			}else{
				$sal_start = '01';
				$prev_month = date("Y-m",strtotime($eff_date_format));
				$date = new DateTime("01-$apply_month 00:00:00");
				$salary_start_date = $date->format("Y-m-$sal_start");	
				$salary_end_date   = date("Y-m-d",strtotime($day_end."-".$apply_month));
			}
		}	
		$diff_check = FALSE;	
		if($effective_date >= $salary_start_date && $effective_date < $salary_end_date){			
			$date = new DateTime("01-$apply_month 00:00:00");
			$date->modify('+1 month');
			$apply_date = $date->format("Y-m-$sal_start");	
			if($eff_month !== $apply_month){
				//Effective Date
				$prev_month = date("Y-m",strtotime($eff_date_format));
				$date_next_month = "$eff_date_format first day of next month";
				$dt_next_month=date_create($date_next_month);
				$next_month = $dt_next_month->format('Y-m');
				$effective_date = $next_month."-".$eff_date;					
			}
			$diff_check = TRUE;	
		}
		$months = $this->get_months($apply_date,$effective_date);
		
		//if($eff_month === $apply_month){	
			$prev_date  = $prev_month."-".$sal_start;
			$array_cum = array();
			$i = 0;	
			$arr = array();		
			//print_r($trans_column); die;
			//column and month wise insert and update
			foreach ($trans_column as $column_name){
				$cumulate_arrear_value = 0;	
				$cumulate_arrear_pf    = 0;
				$arrear_basic          = 0;
				$arrear_gross          = 0;
				foreach ($months as $dt){
					$current_value  = $current_array[$i];
					if((int)$formula_exist > 0){
						$new_value      = $new_array[$column_name];
						$diff_value     = ($new_value) - ($current_value); 
					}else{
						$new_value      = $new_array[$i];
						$diff_value     = $diff_array[$i];
					}
				    $month = $dt->format("m-Y");	

				    $arr_date  = $eff_date."-".$month;
				    //,'.$month_days_db.'	
				    $transaction_qry = 'select '.$paid_days_db.','.$earned_gross_db.','.$earned_basic_db.'  from cw_transactions where transactions_month = "'.$month.'" and employee_code = "'.$employee_code.'" and trans_status = 1';	
					$transaction_data   = $this->db->query("CALL sp_a_run ('SELECT','$transaction_qry')");
					$transaction_result = $transaction_data->result();
					$transaction_data->next_result();
					$paid_days    = $transaction_result[0]->$paid_days_db;
					$month_days   = $this->Process_payroll_model->get_total_work_days($category,$month);
					//echo "BSK $eff_date :: $eff_month === $month :: $prev_date, $eff_date_format"; die;
					if($eff_date !== "01"){
						if($eff_month === $month){
							if((int)$process_by === 1){
								$lop_days = $this->dateDiff($prev_date, $eff_date_format);
								if($sal_start === $eff_date){
									$lop_days   = $after_day;
								}else{
									$lop_days   = $after_day + $lop_days;
								}
								$paid_days  = $month_days - $lop_days;
							}else{
								$paid_days = $after_day;
							}	
						}else{
							if($diff_check){
								$diff_days = $this->dateDiff($prev_date, $effective);
								$paid_days = $month_days - $diff_days;
							}else{
								$paid_days  = $paid_days;
							}							
						}					
					}else{						
						if($eff_month === $month){
							if((int)$process_by === 1){
								$lop_days = $this->dateDiff($prev_date, $eff_date_format);
								if($sal_start === $eff_date){
									$lop_days   = $after_day;
								}else{
									$lop_days   = $after_day + $lop_days;
								}
								$paid_days  = $month_days - $lop_days;
							}else{
								$paid_days = $after_day;
							}
						}else{
							$paid_days  = $paid_days;
						}
					}
				$arrear_column_qry = 'select arrear_column from cw_arrear_column_mapping where transaction_column = "'.$column_name.'" and trans_status = 1';
				$arrear_column_data   = $this->db->query("CALL sp_a_run ('SELECT','$arrear_column_qry')");
				$arrear_column_result = $arrear_column_data->result();
				$arrear_column_data->next_result();
				$arrear_column = $arrear_column_result[0]->arrear_column;			
				if($column_name === $fixed_basic_db){
					$arrear_basic_db = $arrear_column;
				}
				$arrear_value = ((($diff_value * $paid_days) / $month_days));	
				//echo "BSK ($diff_value :: $paid_days :: $month_days :: $arrear_value"; die;
				$arrear_date = date("Y-m-d",strtotime($arr_date));				
				$cumulate_arrear_value       = (($cumulate_arrear_value + $arrear_value));
				$arr[$month][$arrear_column] = $arrear_value;
				
				if($arrear_column){
					$exist_qry = 'SELECT * from cw_arrears where increment_apply_month = "'.$apply_month.'" and employee_code = "'.$employee_code.'" and transaction_column = "'.$column_name.'" and arrear_month = "'.$month.'"';
					$exist_data   = $this->db->query("CALL sp_a_run ('SELECT','$exist_qry')");
					$exist_result = $exist_data->result();
					$exist_data->next_result();
					$exist_rows = $exist_data->num_rows();
					if((int)$exist_rows === 0){
						$insert_query = 'insert into cw_arrears(increment_apply_month,category,employee_code,effective_date,transaction_column,arrear_column,arrear_month,arrear_value,paid_days,arrear_pf,new_value,old_value,arrear_date,trans_created_by,trans_created_date) value ("'.$apply_month.'","'.$category.'","'.$employee_code.'","'.$effective.'","'.$column_name.'","'.$arrear_column.'","'.$month.'","'.$arrear_value.'","'. $paid_days .'","'.$arrear_pf.'","'.$new_value.'","'.$current_value.'","'.$arrear_date.'","'.$this->logged_id.'","'.date('Y-m-d H:i:s').'")';
						$insert_result = $this->db->query("CALL sp_a_run ('RUN','$insert_query')");
					}else{
						$upd_arrears_query   = 'UPDATE cw_arrears SET paid_days = "'. $paid_days .'",arrear_pf = "'. $arrear_pf .'",new_value = "'. $new_value .'",arrear_value = "'. $arrear_value .'",trans_updated_by = "'. $this->logged_id .'",trans_updated_date = "'. $created_on .'" WHERE employee_code = "'. $employee_code .'" and increment_apply_month = "'.$apply_month.'" and transaction_column = "'.$column_name.'" and arrear_date = "'.$arrear_date.'"';					
						$upd_arrears_result = $this->db->query("CALL sp_a_run ('UPDATE','$upd_arrears_query')");				
					}
				}		
			}		
			//echo "BSK $arrear_column :: $arrear_value :: $exist_rows <br/>";
			if($arrear_column){
				/*$exist_qry = 'SELECT * from cw_arrear_cumulative where increment_apply_month = "'.$apply_month.'" and employee_code = "'.$employee_code.'" and transaction_column = "'.$column_name.'" and arrear_month = "'.$month.'"';
					$exist_data   = $this->db->query("CALL sp_a_run ('SELECT','$exist_qry')");
					$exist_result = $exist_data->result();
					$exist_data->next_result();
					$exist_rows = $exist_data->num_rows();*/
				if((int)$exist_rows === 0){
					$cumulate_query = 'insert into cw_arrear_cumulative(increment_approval_id,increment_apply_month,category,employee_code,effective_date,transaction_column,arrear_column,arrear_value,arrear_pf,payroll_done,trans_created_by,trans_created_date) value ("'.$inc_approval_id.'","'.$apply_month.'","'.$category.'","'.$employee_code.'","'.$effective.'","'.$column_name.'","'.$arrear_column.'","'.$cumulate_arrear_value.'","'.$cumulate_arrear_pf.'","Y","'.$this->logged_id.'","'.date('Y-m-d H:i:s').'")';
					$cumulate_result = $this->db->query("CALL sp_a_run ('RUN','$cumulate_query')");
				}else{
					$upd_cumulative_query   = 'UPDATE cw_arrear_cumulative SET arrear_value = "'. $cumulate_arrear_value .'",arrear_pf = "'. $cumulate_arrear_pf .'",trans_updated_by = "'. $this->logged_id .'",trans_updated_date = "'. $created_on .'" WHERE employee_code = "'. $employee_code .'" and increment_apply_month = "'.$apply_month.'" and transaction_column = "'.$column_name.'"';
					$upd_cumulative_result = $this->db->query("CALL sp_a_run ('UPDATE','$upd_cumulative_query')");
				}
			}
			$i++;
		}
		//die;
		//if($arrear_column){
			//$result = $this->calculate_arrear_pf($category,$employee_code,$apply_month,$arrear_gross_db,$arrear_pf_gross_db,$new_value,$arr,$arrear_basic_db,$earned_basic_db,$earned_gross_db,$earned_hra_db,$trans_columns,$arrear_pf_gross_formula);
			//if($result){
				echo json_encode(array('success' => true, 'message' => "Increment Data Successfully Saved"));
			//}else{
				//echo json_encode(array('success' => false, 'message' => "Transaction Columns Not Mapped Correctly"));
			//}
		//}
		//echo json_encode(array('success' => true, 'message' => "Increment Data Successfully Saved"));
	/*}else{			
		echo json_encode(array('success' => true, 'message' => "Increment Data Successfully Saved"));
		}	*/		
	}
	//Arrear PF Calculation
	public function calculate_arrear_pf($trans_columns,$category,$employee_code,$apply_month,$arrear_gross_db,$arrear_pf_gross_db,$arr,$arrear_basic_db,$arrear_pf_gross_formula){
		$created_on           = date("Y-m-d h:i:s");
		//Arrear Gross Formula
		$get_arrear_gross_qry = 'select payroll_formula from cw_payroll_formula where formula_for = "'.$category.'" and out_column = "'.$arrear_gross_db.'"  and trans_status =1';
		$arrear_gross_data   = $this->db->query("CALL sp_a_run ('SELECT','$get_arrear_gross_qry')");
		$arrear_gross_result = $arrear_gross_data->result();
		$arrear_gross_data->next_result();
		$arrear_gross_formula    = $arrear_gross_result[0]->payroll_formula;		
		
		$i = 1;	//for generate dynamic file name and function name
		$cumulate_pf = 0;
		$cumulate_arrear_gross = 0;
		$arrear_gr = 0;
		foreach ($arr as $arrear_month => $value){
			$pf_array = array();
			$code     = "";
			$pf_calculation = $arrear_pf_gross_formula;
			$arrear_gross   = $arrear_gross_formula;
			if($trans_columns){
				foreach ($trans_columns as $trans_column){
					if($trans_column){
						$transaction_qry = 'SELECT '.$trans_column.' from cw_transactions where transactions_month = "'.$arrear_month.'" and employee_code = "'.$employee_code.'" and trans_status = 1';
						$transaction_data = $this->db->query("CALL sp_a_run ('SELECT','$transaction_qry')");
						$transaction_result = $transaction_data->result();
						$transaction_data->next_result();				
						$trans_value    = $transaction_result[0]->$trans_column;
						$pf_calculation = str_replace("@".$trans_column."@", $trans_value, $pf_calculation);
					}					
				}
			}else{
				return false;
			}
			
			foreach ($value as $column => $arrear_value){
				if($column === $arrear_basic_db){
					$arrear_basic = $arrear_value;
				}
				$change_column = "@".$column."@";
				if($column !== $arrear_gross_db){
					$arrear_gr = $arrear_value;
				}
					//$arrear_gross = str_replace($change_column,$arrear_value,$arrear_gross);
					$pf_calculation = str_replace($change_column, $arrear_value, $pf_calculation);
			}
			$rand = (rand(1,100));
			$pf_calculation = str_replace("@".$arrear_gross_db."@",$arrear_gross,$pf_calculation);
			//$arrear_gross = "return $arrear_gross;";
			$filename = "pf_calculation_file_".$rand.".php";
			$pf_calculation_func = "calculation_".$rand;
			//$arrear_gross_func   = "gross_func_".$rand;
			$code = "<?php function $pf_calculation_func(){ $pf_calculation }  function $arrear_gross_func(){ $arrear_gross } ?>";
			$code = "<?php function $pf_calculation_func(){ $pf_calculation } ?>";
			fopen($filename, "w");
			file_put_contents($filename,$code);
			chmod($filename, 0777);
			require_once($filename);
			//$arrear_gr = 0;
			$cumulate_arrear_gross = 0;
			$pf_value    = $pf_calculation_func();
			//$arrear_gr   = $arrear_gross_func();
			$cumulate_pf = $cumulate_pf + $pf_value;
			$cumulate_arrear_gross = $cumulate_arrear_gross + $arrear_gr;
			$upd_arrears_query  = 'UPDATE cw_arrears SET arrear_value = "'. $arrear_gr .'",arrear_pf = "'. $pf_value .'",trans_updated_by = "'. $this->logged_id .'",trans_updated_date = "'. $created_on .'" WHERE employee_code = "'. $employee_code .'" and increment_apply_month = "'.$apply_month.'" and arrear_column = "'.$arrear_gross_db.'" and arrear_month = "'.$arrear_month.'"';							
			$upd_arrears_result = $this->db->query("CALL sp_a_run ('UPDATE','$upd_arrears_query')"); 
			$i++;
			unlink("$filename");
		}		
		if($upd_arrears_result){
			$upd_cumulative_query   = 'UPDATE cw_arrear_cumulative SET arrear_value = "'. $cumulate_arrear_gross .'",arrear_pf = "'. $cumulate_pf .'",trans_updated_by = "'. $this->logged_id .'",trans_updated_date = "'. $created_on .'" WHERE employee_code = "'. $employee_code .'" and increment_apply_month = "'.$apply_month.'" and arrear_column = "'.$arrear_gross_db.'"';
			$upd_cumulative_result = $this->db->query("CALL sp_a_run ('UPDATE','$upd_cumulative_query')");
			return true;
		}
		return true;
	}
	public function increment_formula($trans_array){
		$input_query = 'SELECT * FROM `cw_form_bind_input` 
			INNER JOIN `cw_form_condition_formula` ON cw_form_condition_formula.prime_cond_id = cw_form_bind_input.input_cond_id 
		WHERE input_cond_module_id ="employees" AND cond_order != 0 AND line_input_bind_col !="" AND cw_form_condition_formula.trans_status=1 order by prime_cond_id DESC';
		$input_data   = $this->db->query("CALL sp_a_run ('SELECT','$input_query')");
		$input_result = $input_data->result();
		$input_data->next_result();
		$input_colum = "";
		foreach($input_result as $input){
			$role         = $input->line_input_bind_table;
			$out_colum    = $input->line_input_bind_to;
			$input_colum  = $input->line_input_bind_col;
			$condition_check_form    = $input->condition_check_form;
			$condition_check_form    = explode(",",$condition_check_form);
			if($input_colum){
				foreach($condition_check_form as $check_form){
					if(strpos($input_colum,"@$check_form@") !== false){
						$value = "\$trans_array['".$check_form."']";
						$input_colum = str_replace("@$check_form@",$value, $input_colum);
						$input_colum = str_replace("return","\$trans_array['".$out_colum."'] = ", $input_colum);	
						$data .= "'$check_form' => $value,";					 
					}
				}
			}				
			//$formula_code .= "\n\t\t\t".'if((int)$trans_array["role"] === '.$role."){\n\t\t\t\t$input_colum\n\t\t\t}";	
			 $formula_code .= "\n\t\t\t $input_colum \n\t\t\t";	
		}	
		$formula_code = "\n\t\t".' foreach($trans_array as $trans){ '.$formula_code."\n\t\t  } return \$trans_array; \n\t\t";		
		$dynamic_file_name= "increment_".$this->logged_id.".php";
		unlink("$dynamic_file_name");
		$fname = "increment(\$trans_array)";
		$code = "<?php function $fname{ $formula_code }?>";
		fopen("$dynamic_file_name", "w");
	    file_put_contents("$dynamic_file_name",$code);
	    chmod($dynamic_file_name, 0777);
		require_once("$dynamic_file_name");			
		$final_result_array = increment($trans_array);		
		unlink("$dynamic_file_name");
		return $final_result_array;
	}
	//Get all the months from the effective date.
	public function get_months($apply_date,$effective_date){
		$start    = new DateTime($effective_date);
		$start->modify('first day of this month');
		$end      = new DateTime($apply_date);
		$end->modify('first day of this month');
		$interval = DateInterval::createFromDateString('1 month');
		$period   = new DatePeriod($start, $interval, $end);
		return $period;
	}	
	//get date difference_value	
	public function dateDiff($date1, $date2){
	  $date1_ts = strtotime($date1);
	  $date2_ts = strtotime($date2);
	  $diff = $date2_ts - $date1_ts;
	  return round($diff / 86400);
	}
	public function mail($form_post_data,$employee_code,$form_id,$approval_type,$hr_status){
		//echo "BSK $hr_status"; die;
		if((int)$hr_status === 2){
			$category = $form_post_data['category'];
			$print_arr = array("1"=>14,"2"=>16,"3"=>15);
			$print_type = $print_arr[$approval_type];
			/*if((int)$approval_type === 1){
				$print_type = 9;
			}else
			if((int)$approval_type === 2){
				$print_type = 10;
			}else
			if((int)$approval_type === 3){
				$print_type = 8;
			}*/

			if($this->check_print_design_exists($print_type)){
				$mail_qry = 'SELECT personal_email_id from cw_employees where employee_code = "'.$employee_code.'" and trans_status = 1';
				$mail_data = $this->db->query("CALL sp_a_run ('SELECT','$mail_qry')");
				$mail_result = $mail_data->result();
				$mail_data->next_result();				
				$to_email    = $mail_result[0]->personal_email_id;
				return $this->send_mail($category,$employee_code,$print_type,$to_email,$bcc=array());
			}else{
				return false;
			}
		}				
	}	
	
	public function check_print_design_exists($print_type){
		$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 = "'.$this->control_name.'" and cw_print_design.trans_status = 1 and cw_print_info.print_type IN ("'.$print_type.'")';
		$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 > 0){
			return true;
		}else{
			return false;
		}
	}
	public function send_mail($category,$employee_code,$print_type,$to_email,$bcc){
		$email_design_query  = 'select prime_print_info_id,email_design,print_info_for,print_info_module_id,print_type,email_subject from cw_email_design inner join cw_print_info on cw_print_info.prime_print_info_id = cw_email_design.email_design_for where find_in_set("'.$category.'",print_info_for) and print_info_module_id = "'.$this->control_name.'" and cw_print_info.trans_status = 1 and print_type =14';
		$email_design_info    = $this->db->query("CALL sp_a_run ('SELECT','$email_design_query')");
		$email_design_result  = $email_design_info->result();
		$email_design_info->next_result();
		$email_design_content = $email_design_result[0]->email_design;
		$mail_subject         = $email_design_result[0]->email_subject;
		$email_bcc 			  = explode(",",$email_design_result[0]->email_bcc);
		// $to_email 			  = explode(",",$email_design_result[0]->to_email);
		if($to_email !== ""){			
			$config_query  = 'select smtp_server,sender_name,bcc,port_no,sender_email,mail_username,mail_password from cw_mail_configurations where prime_mail_configurations_id ="1" and trans_status = 1  and mail_status = 1';
			$config_info   = $this->db->query("CALL sp_a_run ('SELECT','$config_query')");
			$config_result = $config_info->result();
			$config_info->next_result();
			$smtp_server     = $config_result[0]->smtp_server;
			$sender_name     = $config_result[0]->sender_name;
			$port_no         = $config_result[0]->port_no;
			$sender_email    = $config_result[0]->sender_email;
			$username        = $config_result[0]->mail_username;
			$mail_password   = $config_result[0]->mail_password;
			//echo "BSK $smtp_server :: $sender_name :: $port_no:: $sender_email :: $username :: $mail_password "; die;
			require('./phpmailer/class.phpmailer.php');
			$mail = new PHPMailer();
			try{
				$mail->SMTPDebug = 3;
				$mail->IsSMTP();
				$mail->Host = $smtp_server; // Your SMTP PArameter
				$mail->Port = $port_no; // Your Outgoing Port
				$mail->SMTPAuth = true; // This Must Be True
				$mail->Username = $username; // Your Email Address
				$mail->Password = $mail_password; // Your Password
				$mail->SMTPSecure = 'tls'; // Check Your Server's Connections for TLS or SSL
				$mail->From     = $sender_email;
				$mail->FromName = $sender_name;
				/*$mail->Host = 'smtp.gmail.com'; // Your SMTP PArameter
				$mail->Port = '587'; // Your Outgoing Port
				$mail->SMTPAuth = true; // This Must Be True
				$mail->Username = 'patroniss.2020@gmail.com'; // Your Email Address
				$mail->Password = 'Welcome@2020'; // Your Password
				$mail->SMTPSecure = 'tls'; // Check Your Server's Connections for TLS or SSL
				$mail->From     = 'patroniss.2020@gmail.com';
				$mail->FromName = "Collman";*/
				if($to_email){		
					$mail->AddAddress($to_email);
				}	
				if((int)count($bcc) > 0){
					foreach ($bcc as $bcc_key => $bcc_mails){
						$mail->AddCC($bcc_mails);
					}
				}

				$mail->IsHTML(true);
				$mail->Subject = $mail_subject;
				$mail->Body    = $email_design_content;
			    $path_name = $this->load_print_info($category,$employee_code,$print_type);
				if(file_exists($path_name)){
					$mail->addAttachment($path_name);	
				}
			    $mail= $mail->Send();
			    if($mail){
			    	$status = 1;
			    	$msg = "Mail Sent Successfully";
				}
			}catch(phpmailerException $e){
				$status = 0;
				$msg = "Mail Not Sent";
			}catch(Exception $e){
				$status = 0;
				$msg = "Mail Not Sent";
			}
		}else{
			$status = 0;
			$msg = "Email ID is empty, so mail is not send";
		}

	}
	public function load_print_info($category,$emp_code,$print_type){
		$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 = "'.$this->control_name.'" 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();
		$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";
				$join_module_name = str_replace("cw_","",$line_join_table);
				$join_prime_id    = "prime_".$join_module_name."_id";
				
				
				if((int)$line_sort === 1){
					if($cutome_table_check[$module_name]){
						$line_prime_table = " $line_prime_table ";
					}else{
						$line_prime_table = " $line_prime_table ";
					}
					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 ";
					}
					$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 "; 
					}
				}
			}
			if(!$line_table_query){
				$module_name      = str_replace("cw_","",$print_block_table);
				$prime_id         = "prime_".$module_name."_id";
				$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($print_design){
							$new_value     = $this->new_value_calculate($emp_code);
							$print_design  = str_replace("@new_value@",$new_value,$print_design);
							$net_pay_words = $this->numbertowords($new_value);
							$net_pay_words = strtoupper($net_pay_words);
							$print_design  = str_replace("@new_value_words@",$net_pay_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);
				}
			}
		}
		$current_date = date("d-m-Y");
		$print_design = str_replace("<br>","",$print_design);
		$print_design = str_replace("@today_date@",$current_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     = "pdf_generation/increment_approval";
		$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;
	}
	public function send_approvalmail($content_id,$emp_id,$manager_mail){
		$email_data     = $this->load_email_data($content_id,$emp_id);
		$body_content   = "<!DOCTYPE html><html> <body>".$email_data['print_design']."</body></html>";
		$email_design_query  = 'SELECT * FROM cw_email_design WHERE email_design_for ="'.$content_id.'" and trans_status=1';
			$email_design_query   = $this->db->query("CALL sp_a_run ('SELECT','$email_design_query')");
			$email_design_result  = $email_design_query->result();
			$email_design_query->next_result();
			$email_design_content = $email_design_result[0]->email_design;
			$to_email  			  = $email_design_result[0]->to_email;
			$mail_subject         = $email_design_result[0]->email_subject;
			$email_bcc 			  = explode(",",$email_design_result[0]->email_bcc);
			// $to_email 			  = explode(",",$email_design_result[0]->to_email);

		if($to_email !== ""){			
			$config_query  = 'select smtp_server,sender_name,bcc,port_no,sender_email,mail_username,mail_password from cw_mail_configurations where prime_mail_configurations_id ="1" and trans_status = 1  and mail_status = 1';
			$config_info   = $this->db->query("CALL sp_a_run ('SELECT','$config_query')");
			$config_result = $config_info->result();
			$config_info->next_result();
			$smtp_server     = $config_result[0]->smtp_server;
			$sender_name     = $config_result[0]->sender_name;
			$port_no         = $config_result[0]->port_no;
			$sender_email    = $config_result[0]->sender_email;
			$username        = $config_result[0]->mail_username;
			$mail_password   = $config_result[0]->mail_password;
			// echo "BSK $smtp_server :: $sender_name :: $port_no:: $sender_email :: $username :: $mail_password "; die;
			require('./phpmailer/class.phpmailer.php');
			$mail = new PHPMailer();
			try{
				// $mail->SMTPDebug = 3;
				$mail->IsSMTP();
				$mail->Host = $smtp_server; // Your SMTP PArameter
				$mail->Port = $port_no; // Your Outgoing Port
				$mail->SMTPAuth = true; // This Must Be True
				$mail->Username = $username; // Your Email Address
				$mail->Password = $mail_password; // Your Password
				$mail->SMTPSecure = 'tls'; // Check Your Server's Connections for TLS or SSL
				$mail->From     = $sender_email;
				$mail->FromName = $sender_name;
				/*$mail->Host = 'smtp.gmail.com'; // Your SMTP PArameter
				$mail->Port = '587'; // Your Outgoing Port
				$mail->SMTPAuth = true; // This Must Be True
				$mail->Username = 'patroniss.2020@gmail.com'; // Your Email Address
				$mail->Password = 'Welcome@2020'; // Your Password
				$mail->SMTPSecure = 'tls'; // Check Your Server's Connections for TLS or SSL
				$mail->From     = 'patroniss.2020@gmail.com';
				$mail->FromName = "Collman";*/
				// echo $to_email;die;
				if($to_email){		
					$mail->AddAddress($to_email);
				}

				if($manager_mail){		
					$mail->AddAddress($manager_mail);
				}	

				if((int)count($email_bcc) > 0){
					foreach ($email_bcc as $bcc_key => $bcc_mails){
						$mail->AddCC($bcc_mails);
					}
				}
				$mail->IsHTML(true);
				$mail->Subject = $mail_subject;
				$mail->Body    = $body_content;
			    $mail= $mail->Send();
			    if($mail){
			    	$status = 1;
			    	$msg = "Mail Sent Successfully";
				}
			}catch(phpmailerException $e){
				$status = 0;
				$msg = "Mail Not Sent";
			}catch(Exception $e){
				$status = 0;
				$msg = "Mail Not Sent";
			}
		}else{
			$status = 0;
			$msg = "Email ID is empty, so mail is not send";
		}

	}
	public function send_approvalmail_calls($first_level,$second_level,$hr_status,$emply_id,$manager_code){
		if((int)$first_level === 2 && (int)$second_level === 1 && (int)$hr_status === 1){
			$content_id = 11;
			$manager_mail ='';
		}else
		if((int)$first_level === 2 && (int)$second_level === 2 && (int)$hr_status === 1){
			$content_id = 13;
			$manager_mail =$manager_code;
		}else
		if((int)$first_level === 2 && (int)$second_level === 2 && (int)$hr_status === 2){
			$content_id = 12;
			$manager_mail ='';
		}else
		if((int)$first_level === 2 && (int)$second_level === 3 && (int)$hr_status === 1){
			$content_id = 14;
			$manager_mail =$manager_code;
		}else
		if((int)$first_level === 2 && (int)$second_level === 2 && (int)$hr_status === 3){
			$content_id = 15;
			$manager_mail ='';
		}
		$this->send_approvalmail($content_id,$emply_id,$manager_mail);
	}
	public function new_value_calculate($emp_code){
		$payroll_map_query = 'select * from cw_payroll_function_map where loc_name="fixed_gross" and trans_status=1';
		$payrol_map_info   = $this->db->query("CALL sp_a_run ('SELECT','$payroll_map_query')");
		$payrol_map_result = $payrol_map_info->result();
		$payrol_map_info->next_result();
		$db_column = $payrol_map_result[0]->db_column;
		$qry = ' and cw_increment_approval.employees ="'.$emp_code.'" GROUP BY cw_increment_approval.apply_month';
		$new_val_qry        = 'select cw_increment.new_value from cw_increment inner join cw_increment_approval on cw_increment_approval.prime_increment_approval_id = cw_increment.increment_approval_id inner join cw_employees on cw_employees.employee_code = cw_increment.employee_code where cw_increment_approval.trans_status=1 and column_name="'.$db_column.'" and cw_increment_approval.hr_status = 2 '.$qry;
		$new_val_info   = $this->db->query("CALL sp_a_run ('SELECT','$new_val_qry')");
		$new_val_result = $new_val_info->result();
		$new_val_info->next_result();
		$new_value    	  = $new_val_result[0]->new_value;
		return $new_value;
	}
	public function hike_fetch_category(){
		$employee_code = $this->input->post("employees");
		$emp_qry        = 'select role from cw_employees where employee_code="'.$employee_code.'" and trans_status=1';
		$emp_info   = $this->db->query("CALL sp_a_run ('SELECT','$emp_qry')");
		$emp_result = $emp_info->result();
		$emp_info->next_result();
		$category = $emp_result[0]->role;
		echo json_encode(array('success'=>true,'category'=>$category));
	}
	/* Increment Custom Code END */
	public function first_level_reporting(){
		$employee_code = $this->input->post("logged_emp_code");
		$emp_qry        = 'select prime_employees_id,employee_code,emp_name from cw_employees where first_level_approval="'.$employee_code.'" and termination_status = 0 and trans_status = 1';
		$emp_info   = $this->db->query("CALL sp_a_run ('SELECT','$emp_qry')");
		$emp_result = $emp_info->result();
		$emp_info->next_result();

		$emp_drop_list = "<option value=''>---- Select Employee ----</option>";
		foreach ($emp_result as $key => $value) {
			$prime_id            = $value->prime_employees_id;
			$employee_name       = $value->emp_name;
			$employee_code       = $value->employee_code;
			$emp_drop_list      .= "<option value='$employee_code'>$employee_code - $employee_name</option>";
		}
		echo $emp_drop_list;
	}
}
?>