MOON
Server: Apache
System: Linux nserver.cafsindia.com 4.18.0-553.104.1.lve.el8.x86_64 #1 SMP Tue Feb 10 20:07:30 UTC 2026 x86_64
User: cafsindia (1002)
PHP: 8.2.30
Disabled: NONE
Upload Files
File: //home/cafsindia/hrms_allyindian_com/application_bk/controllers/Request.php
<?php if ( ! defined('BASEPATH')) exit('No direct script is allowed');
require_once("Action_controller.php");
class Request extends Action_controller{
	public function __construct(){
		parent::__construct('request');
	}
	
	// LOAD PAGE QUICK LINK,FILTERS AND TABLE HEADERS
	public function index(){
		$data['encKey']        = $this->generateKey();
		$this->page_info();
		$data['module_sts']    = (int)$this->module_sts;
		$data['quick_link']    = $this->quick_link;
		$data['pick_list']     = $this->pick_list;
		$data['form_info']     = $this->form_info;
		$data['table_head']    = $this->table_head;
		$data['fliter_list']   = $this->fliter_list;
		$data['freeze_list']   = $this->freeze_list;
		$employee_code         = $this->session->userdata('logged_emp_code');
		$data['components']['weekoff_component']  = $this->time_setting_components();
		/* Custom Code for Component value and Weekoff Component */
		$component_query  = 'SELECT pick_table,pick_list,components FROM cw_general_setting inner join cw_form_setting on cw_form_setting.prime_form_id = cw_general_setting.components WHERE entry_parameter_type = 3 and cw_general_setting.trans_status = 1';
		$component_info   = $this->db->query("CALL sp_a_run ('SELECT','$component_query')");
		$component_result = $component_info->result();
		$component_info->next_result();	
	
		$pick_list   = $component_result[0]->pick_list;
		$pick_table = $component_result[0]->pick_table;
		$components = $component_result[0]->components;
		$pick_list_val   = explode(",",$pick_list);
		$pick_list_val_1 = $pick_list_val[0];
		$pick_list_val_2 = $pick_list_val[1];
		$pick_query = "select $pick_list from $pick_table where trans_status = 1";
		$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
		$pick_result = $pick_data->result();
		
		$pick_data->next_result();
		if($pick_result){
			$pick_key   = array_column($pick_result, $pick_list_val_1);
			$pick_val   = array_column($pick_result, $pick_list_val_2);
			$final_pick = array_combine($pick_key, $pick_val);
		}
		$this->pick_list['component_value']['array_list'] = array("" => "---- Component Value----") + $final_pick;
		$data['master_pick']   = $this->pick_list;
		//LEAVE FINANCIAL YEAR GET FUNCTION
		$leave_financial_info  = $this->get_leave_financial_details();
		$prime_financial_id    = $leave_financial_info[0]->prime_leave_financial_year_id;
		
		//FUNCTION FOR USING TO MANAGE MODULE EDIT VIEW AND CANCEL BUTTON VALIDATION ARRAY GET
		$result                    = $this->request_data_arr($prime_financial_id);
		$data['leave_status_arr']  = $result['leave_status_arr'];
		$data['leave_cancel_arr']  = $result['leave_cancel_arr'];
		$data['emp_cancel_arr']    = $result['emp_cancel_arr'];		
		$this->load->view("$this->control_name/manage",$data);
		//$this->load->view("$this->control_name/form",$data['emp_data']);
	}

	//FUNCTION FOR USING TO MANAGE MODULE EDIT VIEW AND CANCEL BUTTON VALIDATION ARRAY GET
	public function request_data_arr($prime_financial_id){
		$leave_status_query    = 'SELECT prime_request_id,first_approval_leave_status as first_leave_status,second_approval_leave_status as second_leave_status,leave_status,cancellation_request,request_type FROM cw_request WHERE cw_request.trans_status = 1 and financial_setting_id = "'.$prime_financial_id.'"';
		$leave_status_info     = $this->db->query("CALL sp_a_run ('SELECT','$leave_status_query')");
		$leave_status_result   = $leave_status_info->result_array();
		$leave_status_info->next_result();
		
		$rslt                  = array();
		$leave_status_arr      = array();
		$leave_cancel_arr      = array();
		$emp_cancel_arr        = array();
		foreach($leave_status_result as $arr){
			$request_id                    = $arr['prime_request_id'];
			$leave_status                  = $arr['leave_status'];
			$cancel_request                = $arr['cancellation_request'];
			$leave_status_arr[$request_id] = $leave_status;
			$leave_cancel_arr[$request_id] = $cancel_request;
			$emp_cancel_arr[$request_id]   = $arr;
		}
		//ALL ARRAYS ADD TO FINAL ARRAY
		$rslt['leave_status_arr']   = $leave_status_arr;
		$rslt['leave_cancel_arr']   = $leave_cancel_arr;
		$rslt['emp_cancel_arr']     = $emp_cancel_arr;
		return $rslt;
	}
	
	//LOAD TABEL WITH FILTERS
	public function search(){
		$dec_data         = $this->cryptoDecrypt($_POST['Payload']);
		$_POST            = $dec_data['data'];
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Url Expired.. Please refresh the page and try again....'));
			exit(0);
		}	
		$this->search_info();
		$module_sts       = (int)$this->module_sts;
		if(!$module_sts){
			echo json_encode(array('success' => FALSE, 'message' => "Search  Info Query Process Error..!"));
			exit(0);
		}else{
			$draw                = $this->input->post('draw');
			$start               = $this->input->post('start');
			$per_page            = $this->input->post('length');
			$order               = $this->input->post('order');
			$order_col           = $this->input->post('columns');
			$search              = $this->input->post('search');
			$column              = $order[0]['column'];
			$order_sor           = $order[0]['dir'];
			$order_col           = $order_col[$column]['data'];
			$search              = trim($search['value']);
			$search_query        = str_replace("@SELECT@",$this->select_query,$this->base_query);
			
			$search_result       = array();
			//ADDED BASIC,FILTER,COMMON QUERY HERE 
			$role_condition      = "";
			if($this->role_condition){
				$role_condition  = $this->role_condition;
			}
			//CURRENT FINANCIAL YEAR ID
			$leave_financial_info = $this->get_leave_financial_details();
			$prime_financial_id   = $leave_financial_info[0]->prime_leave_financial_year_id;
			
			$fliter_query = "";
			foreach($this->fliter_list as $fliter){
				$label_id         = $fliter->label_name;
				$field_isdefault  = (int)$fliter->field_isdefault;
				$field_type       = (int)$fliter->field_type;
				$prime_form_id 	  = $fliter->prime_form_id;

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

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

			if($search_result === null || $search_result === ''){
				$search_result  = [];
			}

			echo json_encode(array("draw" => intval($draw),"recordsTotal" => $total_count,"recordsFiltered" => $filtered_count,"data" => $search_result));		
		}
	}
	
	//LOAD MODEL PAGE VIEW WITH DATA
	public function view($form_view_id=-1){
		$data['primeId']     = $form_view_id;
		if($form_view_id !== -1){
			//Decrypt prime id from URL
			$decRslt          = $this->cryptoDecrypt(base64_decode(urldecode($form_view_id)));
			$form_view_id     = $decRslt['prime_id'];
			if(!$form_view_id){
				echo json_encode(array('success' => false,'message' => 'Url Expired.. Please refresh the page and try again....','table_data' => ""));
				exit(0);
			}
		}
		//VIEW INFO FUNCTION
		$this->view_info($form_view_id);
		$data['module_sts']             = (int)$this->module_sts;
		//VIEW, FORM INPUT
		$data['view_info']              = $this->view_info;
		$data['form_info']              = $this->form_info;
		$data['formula_result']         = $this->formula_result;//for label color change
		$data['role_based_condition']   = $this->role_based_condition;//for label name readonly options
		
		//DEPENDENT AUTO PICKLIST
		$data['auto_pick']              = $this->depen_auto_list;//dependent auto result			
		$data['condition_list']         = $this->form_condition_list;
		
		/* Custom Code for Weekoff Component */
		$component_query  = 'SELECT pick_table,pick_list,components FROM cw_general_setting inner join cw_form_setting on cw_form_setting.prime_form_id = cw_general_setting.components WHERE entry_parameter_type = 3 and cw_general_setting.trans_status = 1';
		$component_info   = $this->db->query("CALL sp_a_run ('SELECT','$component_query')");
		$component_result = $component_info->result();
		$component_info->next_result();			
		$pick_list   = $component_result[0]->pick_list;
		$pick_table = $component_result[0]->pick_table;
		$components = $component_result[0]->components;
		$pick_list_val   = explode(",",$pick_list);
		$pick_list_val_1 = $pick_list_val[0];
		$pick_list_val_2 = $pick_list_val[1];

		$pick_query = "select $pick_list from $pick_table where trans_status = 1";
		$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
		$pick_result = $pick_data->result();
		$pick_data->next_result();
		if($pick_result){
			$pick_key   = array_column($pick_result, $pick_list_val_1);
			$pick_val   = array_column($pick_result, $pick_list_val_2);
			$final_pick = array_combine( $pick_key, $pick_val);
		}
		$this->pick_list[$components]['array_list'] = array("" => "---- $components ----") + $final_pick;		
		$data['weekoff_comp']   = $this->time_setting_components();		
		$data['all_pick']       = $this->pick_list;
		$data['components']     = $components;	

		//VIEW DATA
		$base_query          = str_replace("@SELECT@",$this->view_select,$this->base_query);
		$form_view_qry       = $base_query .' where '.$this->prime_table.'.'.$this->prime_id.' = '.$form_view_id.' and '.$this->prime_table.'.trans_status = 1';
		$row_view_qry        = 'select * from cw_form_view_setting where  prime_view_module_id = "'.$this->control_name.'" and  form_view_type = "3" and trans_status = 1';

		$view_pro_qry             = [];
		$view_pro_qry[]           = array("return"=>"form_view","qry"=>$form_view_qry);
		$view_pro_qry[]           = array("return"=>"row_view_list","qry"=>$row_view_qry);	

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

		$data['form_view']        = $form_view_rslt;
		
		$row_view_list            = array();
		foreach($row_view_rslt as $view){
			$prime_form_view_id   = $view->prime_form_view_id;
			$row_set_data         = $this->get_row_set_data($prime_form_view_id,$form_view_id);
			$row_view_list[$prime_form_view_id] = $row_set_data;
		}
		$data['row_view_list']         = $row_view_list;
		//FOR DEPENDENT
		$data['get_depend_prime_id']   = $this->get_depend_fun();
		$data['depend_label_id']   	   = $this->depend_label_fun();	
		
		$logged_emp_code      		   = $this->session->userdata('logged_emp_code');
		$data['empdata']               = $this->get_emp_request_data($logged_emp_code);
		$data['leave_details']         = $this->view_leave_details($logged_emp_code);
		$data['permission_details']    = $this->view_permission_details($logged_emp_code);
		$data['employee_code']         = $logged_emp_code;
		$data['max_allow_date']        = $this->company_info[0]->max_allow_date;
		$data['max_date_based']        = $this->company_info[0]->max_date_based;
		$data['mp_treat_time_log']     = $this->company_info[0]->mp_treat_as;

		//Get Employee details based on the logged employee
		$emp_details_rlst = $this->emp_details($logged_emp_code);
		$data['date_of_joining']       = date("d-m-Y",strtotime($emp_details_rlst[0]->date_of_joining));
		$data['component_value']       = $emp_details_rlst[0]->$component;
		$data['approve_type']          = $emp_details_rlst[0]->approve_type;
		//Get salary day info
		$month_day_info                = $this->tos_day_info($employee_code,"3"); // 3 => Leave Entry
		$data['salary_start_date']     = $month_day_info['salary_start_date'];
		$data['salary_end_date']       = $month_day_info['year_end_date'];
		$data['fin_start_date']        = date("d-m-Y",strtotime($month_day_info['starting_date']));
		$data['fin_end_date']          = date("d-m-Y",strtotime($month_day_info['ending_date']));
		$data['encKey']                   = $this->generateKey();
		$this->load->view("$this->control_name/form",$data);
	}

	//SAVE MODEL DATA TO DATABASE
	public function save(){
		$encString           = file_get_contents('php://input');
		$_POST               = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Url Expired.. Please refresh the page and try again....','table_data' => ""));
			exit(0);
		}
		//SAVE INFO FUNCTION
		$this->save_info();	
		if($this->config->item("db_name") === 'tcl_hrms' || $this->config->item("db_name") === 'tcl_dev'){
			$logged_emp_code   = $this->input->post('employee_code');
		}else{
			$logged_emp_code   = $this->session->userdata('logged_emp_code');
		}
		
		$module_sts            = (int)$this->module_sts;
		$mp_treat_time_log     = (int)$this->company_info[0]->mp_treat_as;

		if(!$module_sts){
			echo json_encode(array('success' => FALSE, 'message' => "Save Info Query Process Error.!"));
			exit(0);
		}else{
			$post_data           = array();
			$unq_chk             = array();
			$prime_qry_key       = "";
			$prime_qry_value     = "";
			$prime_upd_query     = "";
			$form_id             = $this->input->post($this->prime_id);	
			
			if($form_id !== '-1'){ //Decryption
				$decRslt     = $this->cryptoDecrypt(base64_decode(urldecode($form_id)));
				$form_id     = (int)$decRslt['prime_id'];
				if(!$form_id){
					echo json_encode(array('success' => false,'message' => 'Url Expired.. Please refresh the page and try again....','table_data' => ""));
					exit(0);
				}
			}else{
				$form_id = 0;
			}
			
			$financial_info      = $this->get_leave_financial_details();
			$prime_financial_id  = $financial_info[0]->prime_leave_financial_year_id;
			$fin_start_date      = date("Y-m-d",strtotime($financial_info[0]->starting_date));
			$fin_end_date        = date("Y-m-d",strtotime($financial_info[0]->ending_date));
			foreach($this->form_info as $setting){
				$field_type      = $setting->field_type;
				$input_view_type = (int)$setting->input_view_type;
				$label_id        = strtolower(str_replace(" ","_",$setting->label_name));
				$field_isdefault = $setting->field_isdefault;
				$unique_field    = (int)$setting->unique_field;
				$view_name       = $setting->view_name;
				$date_type       = $setting->date_type;	
				
				if((int)$field_type === 7){
					$multi_name = $label_id."[]";
					$value = trim(implode(",",$this->input->post($multi_name) ?? []));
				}else{
					$value = trim($this->input->post($label_id));
				}
				
				if((int)$field_type === 4){
					if((int)$date_type === 1){
						$value = date('Y-m-d',strtotime($value));
					}else{
						$value = $value;
					}
				}else
				if((int)$field_type === 13){
					$value = date('Y-m-d H:i:s',strtotime($value));
				}	
				$value     = str_replace('"',"~",$value);
				$value     = str_replace("'","`",$value);
				$value     = str_replace("&","^",$value);			
				
			//For replace special character
				$value = str_replace('"',"~",$value);
				$value = str_replace("'","`",$value);	
			
			//Sanitize SQL InJection chars
			$value = $this->sanitize_input($value, $field_type);
			if(($input_view_type === 1) || ($input_view_type === 2)){
				if((int)$field_isdefault === 1){
						if($label_id !== 'employee_code'){
							$prime_qry_key     .= $label_id.",";
							$prime_qry_value   .= '"'.$value.'",';
							$prime_upd_query   .= $label_id.' = "'.$value.'",';
							$post_data[$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,);
						}
					}
				}
				if($label_id === "employee_code"){
					$employee_code = $value;
				}
				if($label_id === "request_type"){
					$request_type = $value;
				}else
				if($label_id === "leave_status"){
					$leave_status = (int)$value;
				}else
				if($label_id === "cancellation_request"){					
					$cancellation_request = $value;
				}else
				if($label_id === "cancellation_reason"){
					$cancellation_reason= $value;
				}
			}			
			$post_data['leave_status'] = 1;
			$leave_status              = 1;
			if((int)$cancellation_request === 1){
				$prime_upd_query   .= 'first_approval_cancel_status="1",second_approval_cancel_status = "1",leave_status = "1",';
				$post_data['first_approval_cancel_status']  = 1;
				$post_data['second_approval_cancel_status'] = 1;				
			}
			// //Update query if employee applied cancellation
			$component_query  = 'SELECT pick_table,label_name,components FROM cw_general_setting inner join cw_form_setting on cw_form_setting.prime_form_id = cw_general_setting.components WHERE entry_parameter_type = 3 and cw_general_setting.trans_status  = 1';
			$component_info   = $this->db->query("CALL sp_a_run ('SELECT','$component_query')");
			$component_result = $component_info->result();
			$component_info->next_result();			
			$label_name       = $component_result[0]->label_name;

			$common_emp_details_qry    = 'select employee_code,date_of_joining,department,first_level_approval,second_level_approval,approve_type as leave_approve_type,department,'.$label_name.' as component_value,device_code FROM cw_employees WHERE trans_status=1 AND employee_code="'.$logged_emp_code.'"';
			$emp_data_info             = $this->db->query("CALL sp_a_run ('SELECT','$common_emp_details_qry')");
			$emp_data_result           = $emp_data_info->result();
			$emp_data_info->next_result();
			$first_level_approval      = $emp_data_result[0]->first_level_approval;
			$second_level_approval     = $emp_data_result[0]->second_level_approval;
			if(($first_level_approval === "" || $first_level_approval === "0") && ($second_level_approval === "" || $second_level_approval === "0")){
				echo json_encode(array('success' => FALSE, 'message' => "Approver Details Not Mapped in Employee Master.!"));
				exit(0);
			}
			foreach($emp_data_result[0] as $key => $val){
				$post_data[$key]     = $val; 				
				$prime_qry_key      .= $key.",";
				$prime_qry_value    .= '"'.$val.'",';			
			}			
			$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
			if((int)$cancellation_request === 2 && (int)$leave_status === 2){
				echo json_encode(array('success' => false, 'message' => 'Already Your Leave Status Was Updated!!'));
			}else{
				$created_on = date("Y-m-d H:i:s");
				if((int)$form_id === 0){
					# FINANCIAl YEAR VALIDATION.
					if($request_type){
						$check_finyear_validation = $this->check_finyear_validation($post_data,$fin_start_date,$fin_end_date);
						if((int)$check_finyear_validation !== 1){
							exit(0);
						}	
					}
					# ONE REQUEST PER DAY -> NB[16-02-2024]
					if($this->config->item("db_name") === 'rebar_hrms_db'){ 
						$check_perday_validation = $this->check_perday_validation($post_data,$request_type);
						if((int)$check_perday_validation !== 1){
							exit(0);
						}
					}
					if($request_type === "1" || $request_type === "2" || $request_type === "3" || $request_type === "8"){
						$check_leave_validation      = $this->check_leave_validation($post_data);
						if((int)$check_leave_validation !== 1){
							exit(0);
						}
					}else
					if($request_type === "4" || $request_type === "5"){
						$check_permission_validation = $this->check_permission_validation($post_data);
						if((int)$check_permission_validation !== 1){
							exit(0);
						}
					}else
					if($request_type === "6"){
						$check_shift_change_valid    = $this->shift_change_validation($post_data);
						if((int)$check_shift_change_valid !== 1){
							exit(0);
						}
					}else
					if($request_type === "7"){
						$check_manual_punch_valid    = $this->manual_punch_validation($post_data);
						if((int)$check_manual_punch_valid !== 1){
							exit(0);
						}
					}	
					if((int)$mp_treat_time_log === 2){						
						$check_common_validation         = $this->common_validation($post_data);
						if((int)$check_common_validation !== 1){
							exit(0);
						}
					}	
					$prime_qry_key     .= "financial_setting_id,trans_created_by,trans_created_date";
					$prime_qry_value   .= '"'.$prime_financial_id.'","'.$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)$insert_id){
						if((int)$request_type === 1 || (int)$request_type === 2 || (int)$request_type === 3 || (int)$request_type === 8){
							$this->leave_entry($post_data,$insert_id,$prime_financial_id);
						}else
						if($request_type === "4"){
							$this->permission_entry($post_data,$insert_id,$prime_financial_id);
						}else
						if($request_type === "6"){
							$this->shift_change_entry($post_data,$insert_id,$prime_financial_id);
						}else
						if($request_type === "7"){
							$this->manual_punch_entry($post_data,$insert_id,$prime_financial_id);
						}
					}
					//FUNCTION FOR USING TO MANAGE MODULE EDIT VIEW AND CANCEL BUTTON VALIDATION ARRAY GET
					$result            = $this->request_data_arr($prime_financial_id);

					$leave_status_arr  = $result['leave_status_arr'];
					$leave_cancel_arr  = $result['leave_cancel_arr'];
					$emp_cancel_arr    = $result['emp_cancel_arr'];

					echo json_encode(array('success' => TRUE, 'message' => "Request Successfully added $send_mail_status", 'insert_id' => $insert_id, 'leave_status_arr' => $leave_status_arr, 'leave_cancel_arr' => $leave_cancel_arr, 'emp_cancel_arr' => $emp_cancel_arr));
				}else{
					//CANCEL REQUEST
					if((int)$cancellation_request === 1){
						//if overtime is greater than zero don't allow to delete(delete ot request and the request other)
						$employee_code         = $post_data['employee_code'];
						$request_date          = $post_data['request_date'];
						if($employee_code && $request_date){
							$ot_check_qry          = 'select sum(over_time) as over_time from cw_overtime_entry where employee_code="'.$employee_code.'" and entry_date = "'.$request_date.'"';
							$over_time_info        = $this->db->query("CALL sp_a_run ('SELECT','$ot_check_qry')");
							$over_time_rslt        = $over_time_info->result_array();
							$over_time_info->next_result();
							$over_time             = $over_time_rslt[0]->over_time;
							if($over_time > 0){
								echo json_encode(array("success"=>false,"message"=>"Overtime already exist in this date please cancel...!"));
								exit(0);
							}
						}
						$this->cancel_entry($post_data,$form_id,$cancellation_request,$cancellation_reason);
						$prime_upd_query   .= 'trans_updated_by = "'. $this->logged_id .'",trans_updated_date = "'.$created_on.'"';
						$prime_update_query = 'UPDATE '. $this->prime_table .' SET '. $prime_upd_query .' WHERE '. $this->prime_id .' = "'. $form_id .'"';
						$this->db->query("CALL sp_a_run ('UPDATE','$prime_update_query')");

						//FUNCTION FOR USING TO MANAGE MODULE EDIT VIEW AND CANCEL BUTTON VALIDATION ARRAY GET
						$result            = $this->request_data_arr($prime_financial_id);

						$leave_status_arr  = $result['leave_status_arr'];
						$leave_cancel_arr  = $result['leave_cancel_arr'];
						$emp_cancel_arr    = $result['emp_cancel_arr'];

						echo json_encode(array('success' => TRUE, 'message' => "Successfully updated $send_mail_status",'insert_id' => $form_id, 'leave_status_arr' => $leave_status_arr, 'leave_cancel_arr' => $leave_cancel_arr, 'emp_cancel_arr' => $emp_cancel_arr));
					}
				}
			}
		}
	}
	//direct cancel process without approval
	public function emp_request_cancel(){
		//Decrypt prime id from URL
		$decRslt               = $this->cryptoDecrypt(base64_decode(urldecode($this->input->post('Payload'))));
		$prime_id              = $decRslt['prime_id'];
		if(!$prime_id){
			echo json_encode(array('success' => false,'message' => 'Url Expired.. Please refresh the page and try again....','table_data' => ""));
			exit(0);
		}
		$created_on            = date("Y-m-d H:i:s");	
		$leave_financial_info  = $this->get_leave_financial_details();
		$prime_financial_id    = $leave_financial_info[0]->prime_leave_financial_year_id;
		
		// ,cw_request.employee_code,cw_request.request_type,cw_request.leave_type,cw_request.no_of_days
		$exist_request_qry     = 'SELECT cw_request.*,count(prime_request_id) as count,cw_employees.role FROM cw_request inner join cw_employees on cw_employees.employee_code = cw_request.employee_code WHERE prime_request_id = "'.$prime_id.'" and financial_setting_id = "'.$prime_financial_id.'" and first_approval_leave_status = 1 and second_approval_leave_status = 1 and cancellation_request = 2 and cw_employees.trans_status = 1 and cw_request.trans_status = 1';
		$exist_request_info   = $this->db->query("CALL sp_a_run ('SELECT','$exist_request_qry')");
		$exist_request_rslt   = $exist_request_info->result();
		$exist_request_info->next_result();

		$exist_count          = (int)$exist_request_rslt[0]->count;
		$category             = (int)$exist_request_rslt[0]->role;
		$employee_code        = $exist_request_rslt[0]->employee_code;
		$request_type         = (int)$exist_request_rslt[0]->request_type;
		$leave_type           = (int)$exist_request_rslt[0]->leave_type;
		$no_of_days           = $exist_request_rslt[0]->no_of_days;
		$from_date            = $exist_request_rslt[0]->from_date;
		$to_date              = $exist_request_rslt[0]->to_date;

		//request type based to get a request date for check a salary start date
		if($request_type === 1 || $request_type === 3 || $request_type === 8){
			$request_date      = date("Y-m-d",strtotime($exist_request_rslt[0]->from_date));
		}else
		if($request_type === 4 || $request_type === 5){
			$request_date      = date("Y-m-d",strtotime($exist_request_rslt[0]->permission_date));
		}else
		if($request_type === 7 || $request_type === 6){
			$request_date      = date("Y-m-d",strtotime($exist_request_rslt[0]->shift_date));
		}
		//To month day query for get salary process month details
        $month_day_info       = $this->tos_day_info($employee_code,"3"); // 3 => Leave Entry

		if(count($month_day_info)){
			$salary_start_date    =  date("Y-m-d",strtotime($month_day_info['salary_start_date']));
			$salary_end_date      =  date("Y-m-d",strtotime($month_day_info['salary_end_date']));
			if($exist_count === 1){
				$table_name           = "";
				$where_cond           = "";
				if($salary_start_date > $request_date){
					echo json_encode(array('success' => FALSE, 'message' => "Past Payroll Transaction Entry should not Cancel.!"));
				}else{
					//IF REQUEST TYPE WAS LEAVE THEN UPDATE LEAVE BALANCE COUNT TO LEAVE OPENING TABLE
					if($request_type === 1){
						//select query for get a leave name and leave opening
						$leave_name_query     = 'SELECT lower(leave_name) as leave_name,leave_opening FROM cw_leave_creation WHERE trans_status = 1 and prime_leave_creation_id = "'.$leave_type.'"';
						$leave_name_info      = $this->db->query("CALL sp_a_run ('SELECT','$leave_name_query')");
						$leave_name_rslt      = $leave_name_info->result();
						$leave_name_info->next_result();
						$leave_opening        = (int)$leave_name_rslt[0]->leave_opening;
						$leave_name           = $leave_name_rslt[0]->leave_name;

						if($leave_opening === 1){
							//SELECT QUERY FOR GET A EMPLOYEE LEAVE BALANCE COUNT FROM LEAVE OPENING
							$leave_count_qry     = 'SELECT '.$leave_name.' as leave_count,pending_'.$leave_name.' as pending_count FROM cw_leave_opening WHERE cw_leave_opening.employee_code = "'.$employee_code.'" and cw_leave_opening.financial_setting_id = "'.$prime_financial_id.'" and cw_leave_opening.trans_status = 1';
							$leave_count_info    = $this->db->query("CALL sp_a_run ('SELECT','$leave_count_qry')");
							$leave_count_rslt    = $leave_count_info->result();
							$leave_count_info->next_result();
							$leave_count         = $leave_count_rslt[0]->leave_count;
							$pending_count       = $leave_count_rslt[0]->pending_count;
							$fin_leave_count     = $leave_count + $no_of_days;
							$fin_pending_count   = $pending_count - $no_of_days;

							//TO UPDATE A LEAVAE BALANCE COUNT TO LEAVE OPENING TABLE FOR THAT EMPLOYEE
							$leave_count_upd_qry = 'UPDATE cw_leave_opening SET pending_'.$leave_name.' = "'.$fin_pending_count.'",trans_updated_by = "'.$this->logged_id .'",trans_updated_date = "'.$created_on.'" WHERE cw_leave_opening.employee_code = "'.$employee_code.'" and cw_leave_opening.financial_setting_id = "'.$prime_financial_id.'" and cw_leave_opening.trans_status = 1';
							$this->db->query("CALL sp_a_run ('UPDATE','$leave_count_upd_qry')");
						}
					}
					//request delete qry
					$request_update_qry   = 'UPDATE '. $this->prime_table .' SET trans_status = "0",trans_deleted_by = "'.$this->logged_id .'",trans_deleted_date = "'.$created_on.'" WHERE '. $this->prime_id .' = "'. $prime_id .'"';
					$this->db->query("CALL sp_a_run ('UPDATE','$request_update_qry')");

					//approval delete qry
					$approval_update_qry  = 'UPDATE cw_approval SET trans_status = "0",trans_deleted_by = "'.$this->logged_id .'",trans_deleted_date = "'.$created_on.'" WHERE cw_approval.prime_request_id = "'. $prime_id .'"';
					$this->db->query("CALL sp_a_run ('UPDATE','$approval_update_qry')");
					//FOR SHIFT CHANGE
					if($request_type === 6){
						echo json_encode(array('success' => true, 'message' => 'Successfully Deleted.!'));
					}else{
						//REQUEST BASED ARRAY CREATION FOR UPDATE A REQUEST
						$tbl_arr              = array(1=>'cw_leave_entry',3=>'cw_on_duty_entry',4=>'cw_permission_entry',5=>'cw_permission_entry',7=>'cw_manual_punch_entry',8=>'cw_on_duty_entry');
				
						//delete qry process
						$request_entry_upd_qry  = 'UPDATE '.$tbl_arr[$request_type].' SET trans_status = "0",trans_deleted_by = "'.$this->logged_id .'",trans_deleted_date = "'.$created_on.'" WHERE '.$tbl_arr[$request_type].'.prime_request_id = "'. $prime_id .'"';
						$this->db->query("CALL sp_a_run ('UPDATE','$request_entry_upd_qry')");

						//FOR TIME ENTRY ACTION STATUS CHECK AND UPDATE 
						$time_entry_qry      = 'select att_date,action_status from cw_time_entry where cw_time_entry.employee_code = "'.$employee_code.'" and cw_time_entry.att_date between ("'.$from_date.'") and ("'.$to_date.'") and cw_time_entry.trans_status = 1';
						$time_entry_info     = $this->db->query("CALL sp_a_run ('SELECT','$time_entry_qry')");
						$time_entry_result   = $time_entry_info->result_array();
						$time_entry_info->next_result();

						$time_entry_arr      = array();
						foreach($time_entry_result as $time_val){
							$time_att_date                   = $time_val['att_date']; 
							$time_action_status              = (int)$time_val['action_status']; 
							//PUSH TO ACTION STATUS (ACTION TAKEN) ONLY  
							// if($time_action_status === 2){
								$time_entry_arr[$time_att_date]  = $time_att_date;
							// }
						}
						$att_date_where      = implode('","',$time_entry_arr);
						//FOR TIME ENTRY ACTION STATUS UPDATE 
						if($att_date_where){
							$upd_time_entry = 'UPDATE cw_time_entry SET action_status = "1",trans_updated_by = "'.$this->logged_id.'", trans_updated_date = "'.$created_on.'" WHERE cw_time_entry.employee_code = "'.$employee_code.'" and cw_time_entry.att_date in ("'.$att_date_where.'") and cw_time_entry.trans_status = 1';
							$upd_info       = $this->db->query($upd_time_entry);
							if($upd_info){
								echo json_encode(array('success' => true, 'message' => 'Successfully Deleted.!'));
							}else{
								echo json_encode(array('success' => false, 'message' => 'Request Could not Delete.!'));
							}
						}else{
							echo json_encode(array('success' => false, 'message' => 'Request Could not Delete.!'));
						}
					}
				}		
			}else{
				echo json_encode(array('success' => false, 'message' => 'Request Could not Delete.!'));
			}
		}else{
			echo json_encode(array('success' => FALSE, 'message' => "Please Set Month Day for this Category.!"));
		}
	}

	public function common_validation($post_data){				
		$request_type          = (int)$post_data["request_type"];
		$employee_code         = $post_data["employee_code"];	
		$device_code           = $post_data["device_code"];		
		$mp_treat_time_log     = (int)$this->company_info[0]->mp_treat_as;

		if($request_type === 1 || $request_type === 3 || $request_type === 8){
			$from_date         = $post_data['from_date'];  
			$to_date           = $post_data["to_date"];
			$from_date_type    = (int)$post_data["from_date_type"];
			$to_date_type      = (int)$post_data["to_date_type"];  
		}else
		if($request_type === 4 || $request_type === 5){
			$from_date         = $post_data['permission_date'];
			$to_date           = $post_data['permission_date'];
		}else
		if($request_type === 7){
			$from_date         = date("Y-m-d",strtotime($post_data["shift_date"]));
			$to_date           = date("Y-m-d",strtotime($post_data["shift_date"]));
			$in_date 	       = date("Y-m-d",strtotime($post_data["in_date"]));
            $in_time           = $post_data["in_time"];
            $out_date 	       = date("Y-m-d",strtotime($post_data["out_date"]));
            $out_time          = $post_data["out_time"];
			$total_time        = $post_data["total_time"];
			$day_type          = $post_data["day_type"];
			$in_date_time      = date('Y-m-d H:i', strtotime($in_date.' '.$in_time));
            $out_date_time     = date('Y-m-d H:i', strtotime($out_date.' '.$out_time));
		}
		
		if($request_type === 1 || $request_type === 3 || $request_type === 7){
			$leave_onduty_entry_arr  = $this->build_common_valid_array(); //function for build array (leave_entry,onduty_entry table)
			if($from_date < $to_date){
				$a = new DateTime($from_date);
				$b = new DateTime($to_date);
				$str_date = $a->format('Y-m-d');
				$finish_date = $b->format('Y-m-d');
				$start_date = clone $a; // Use clone to avoid modifying the original $a object
				$end_date = clone $b;		
				// Create a DatePeriod object to iterate over the range of dates
				$date_interval = new DateInterval('P1D'); // 1 day interval
				$date_range = new DatePeriod($start_date, $date_interval, $end_date);
		
				foreach ($date_range as $date) {
					$chk_date = $date->format('Y-m-d');
					if ($chk_date !== $str_date && $chk_date !== $finish_date) {
						$date_count_val = $leave_onduty_entry_arr[$employee_code][$chk_date];
						if ($date_count_val) {
							$multiple_date_arr[$employee_code] = [$chk_date];
						}
					}
				}
			}
			$from_check_val          = $leave_onduty_entry_arr[$employee_code][$from_date][$from_date_type];
			$to_check_val            = $leave_onduty_entry_arr[$employee_code][$to_date][$to_date_type];
			$date_count_val          = $leave_onduty_entry_arr[$employee_code][$from_date][1] + $leave_onduty_entry_arr[$employee_code][$from_date][2] + $leave_onduty_entry_arr[$employee_code][$from_date][3];
			// Iterate through the dates and add them to the array
			$mp_entry_qry            = 'select count(*)as mp_exist_count from cw_manual_punch_entry where employee_code="'.$employee_code.'" and shift_date="'.$shift_date.'" and day_type ="'.$day_type.'" and leave_status in(1,2)';
			$mp_entry_info         = $this->db->query("CALL sp_a_run ('SELECT','$mp_entry_qry')");
			$mp_entry_result       = $mp_entry_info->result_array();
			$mp_entry_info->next_result();
			$mp_exist_count        = $mp_entry_result[0]['mp_exist_count'];
			if($from_check_val || $to_check_val){
				echo json_encode(array("success"=>false,"message"=>"Leave or Onduty Already Applied For this Date type...!"));
				exit(0);
			}else
			if((int)$date_count_val >= 1){
				echo json_encode(array("success"=>false,"message"=>"Leave or Onduty Already Applied For this Date...!"));
				exit(0);
			}else
			if((int)$mp_exist_count > 0){
				echo json_encode(array("success"=>false,"message"=>"Manual punch Already Exist in this data...!"));
				exit(0);
			}else
			if($multiple_date_arr){
				echo json_encode(array("success"=>false,"message"=>"Leave or Onduty Already applied for inbetween date...!"));
				exit(0);
			}else{
				return true;
			}
		}else{
			return true;
		}
	}

	public function check_finyear_validation($post_data, $fin_start_date, $fin_end_date){
		$fin_start_date_dmy = date("d-m-Y", strtotime($fin_start_date));
    	$fin_end_date_dmy   = date("d-m-Y", strtotime($fin_end_date));
	    $dates_to_check     = array("shift_date" => "Shift date","permission_date" => "Permission date","from_date" => "From date","to_date" => "To date");
	    foreach($dates_to_check as $date_key => $date_label){
	        $date = $post_data[$date_key];
	        if($date !== '1970-01-01'){
		        if(!($date >= $fin_start_date && $date <= $fin_end_date)){
		            echo json_encode(array("success" => false, "message" => "$date_label should be in this financial year [ $fin_start_date_dmy To $fin_end_date_dmy ]"));
		            exit(0);
		        }else{
					return true;
				}
	        }
	    }
	}

	public function check_perday_validation($post_data,$request_type){
		$component_value = $post_data["component_value"];
		$employee_code   = $post_data["employee_code"];
		$shift_date 	 = $post_data["shift_date"];
		$permission_date = $post_data["permission_date"];
		$from_date  	 = $post_data["from_date"];
		$to_date      	 = $post_data["to_date"];					
		$sd_qry          = "";
		$pd_qry          = "";
		$od_qry          = "";
		$lv_qry          = "";
		//MANUAL,SHIFT.
		if($request_type === "6" || $request_type === "7"){
			$sd_qry      = 'AND shift_date = "'.$shift_date.'"';	
			$pd_qry      = 'AND permission_date = "'.$shift_date.'"';	
			$lv_qry      = 'AND leave_date >= "'.$shift_date.'" AND leave_date <= "'.$shift_date.'"';	
			$od_qry      = 'AND on_duty_date >= "'.$shift_date.'" AND on_duty_date <= "'.$shift_date.'"';		
		}else
		//PERMISSION.
		if($request_type === "4"){			
			$sd_qry      = 'AND shift_date = "'.$permission_date.'"';	
			$pd_qry      = 'AND permission_date = "'.$permission_date.'"';
			$lv_qry      = 'AND leave_date >= "'.$permission_date.'" AND leave_date <= "'.$permission_date.'"';	
			$od_qry      = 'AND on_duty_date >= "'.$permission_date.'" AND on_duty_date <= "'.$permission_date.'"';
		}else
		//LEAVE,ONDUTY,BUSINESS TRIP.
		if($request_type === "1" || $request_type === "3" || $request_type === "8"){			
			$sd_qry      = 'AND shift_date >= "'.$from_date.'" AND shift_date <= "'.$to_date.'"';
			$pd_qry      = 'AND permission_date >= "'.$from_date.'" AND permission_date <= "'.$to_date.'"';
			$lv_qry      = 'AND leave_date >= "'.$from_date.'" AND leave_date <= "'.$to_date.'"';	
			$od_qry      = 'AND on_duty_date >= "'.$from_date.'" AND on_duty_date <= "'.$to_date.'"';
		}
		$shift_qry       = 'SELECT count(employee_code) AS count FROM cw_request WHERE employee_code= "'.$employee_code.'"  '.$sd_qry.' AND leave_status IN (1,2) AND trans_status = 1';
		$shift_info      = $this->db->query("CALL sp_a_run ('SELECT','$shift_qry')");
		$shift_rslt      = $shift_info->result();
		$shift_info->next_result();

		$permission_qry  = 'SELECT count(employee_code) AS count FROM cw_request WHERE employee_code= "'.$employee_code.'" '.$pd_qry.' AND leave_status IN (1,2) AND trans_status = 1';
		$permission_info = $this->db->query("CALL sp_a_run ('SELECT','$permission_qry')");
		$permission_rslt = $permission_info->result();
		$permission_info->next_result();

		$on_duty_qry     = 'SELECT count(employee_code) AS count FROM cw_on_duty_entry WHERE employee_code = "'.$employee_code.'" '.$od_qry.' AND on_duty_status IN (1,2) AND trans_status = 1';
		$on_duty_info    = $this->db->query("CALL sp_a_run ('SELECT','$on_duty_qry')");
		$on_duty_rslt    = $on_duty_info->result();
		$on_duty_info->next_result();	

		$leave_qry       = 'SELECT count(employee_code) AS count FROM cw_leave_entry WHERE employee_code = "'.$employee_code.'" '.$lv_qry.' AND leave_status IN (1,2) AND trans_status = 1';
		$leave_info      = $this->db->query("CALL sp_a_run ('SELECT','$leave_qry')");
		$leave_rslt      = $leave_info->result();
		$leave_info->next_result();
		//FINAL VALIDATION.
		if((int)$shift_rslt[0]->count > 0 || (int)$permission_rslt[0]->count > 0 || (int)$on_duty_rslt[0]->count > 0 || (int)$leave_rslt[0]->count > 0){
			echo json_encode(array('success' => false, 'message' => "Exceeded limit - One Request per day."));
			exit(0);
		}else{
			return true;
		}
	}

	public function check_leave_validation($post_data){
		$component_value       = $post_data["component_value"];
		$request_type          = (int)$post_data["request_type"];
		$employee_code         = $post_data["employee_code"];
		$leave_type            = $post_data["leave_type"];
		$leave_balance         = $post_data["leave_balance"];
		$from_date 	           = $post_data["from_date"];
		$from_date_type        = (int)$post_data["from_date_type"];
		$to_date 	           = $post_data["to_date"];
		$to_date_type          = (int)$post_data["to_date_type"];  
		$no_of_days            = $post_data["no_of_days"];
		$leave_financial_info  = $this->get_leave_financial_details();
		$prime_financial_id    = $leave_financial_info[0]->prime_leave_financial_year_id;
		$salary_start_date     = "";
		$salary_end_date       = "";
		$year_end_date         = "";
		//TIME OF SETTING BASED SALARY START AND END DATE DETAILS
		$month_day_info        = $this->tos_day_info($employee_code,"3"); // 3 => Leave Entry
		$salary_start_date     = date("Y-m-d",strtotime($month_day_info["salary_start_date"]));
		$salary_end_date       = date("Y-m-d",strtotime($month_day_info["salary_end_date"]));
		$year_end_date         = date("Y-m-d",strtotime($month_day_info["year_end_date"]));
		//for Get Leave Creation
		$leave_creation_qry    = 'SELECT coff,coff_late,is_el,leave_description,leave_category from cw_leave_creation where cw_leave_creation.trans_status = 1 and prime_leave_creation_id = "'.$leave_type.'"';
		$leave_creation_info   = $this->db->query("CALL sp_a_run ('SELECT','$leave_creation_qry')");
		$leave_creation_result = $leave_creation_info->result();
		$leave_creation_info->next_result();
		$coff 	               = $leave_creation_result[0]->coff;
		$coff_late 	           = $leave_creation_result[0]->coff_late;
		$is_el 	               = $leave_creation_result[0]->is_el;
		$leave_description     = $leave_creation_result[0]->leave_description;
		$leave_category        = (int)$leave_creation_result[0]->leave_category;
		$pending_column 	   = "pending_".$leave_name;
		if($request_type === 1){ // check for Leave
			if((int)$coff_late === 1){ // For Coff Late created for Rebar
				if(($from_date === $to_date) && (int)$from_date_type === 2 && (int)$to_date_type === 2){
					$this->check_coff_late($employee_code,$from_date);
				}else{
					echo json_encode(array('success' => FALSE, 'message' => "Coff Late will be available for the Next Day first Half only.!"));
					exit(0);
				}				
			}
			if((int)$coff === 1){ // Check Coff Balance Exist or not
				$coff_count = $this->check_coff_exist($employee_code,$prime_financial_id,$from_date);
				if($coff_count < $no_of_days){
					echo json_encode(array('success' => false, 'message' => "Compensatory Leave Date should be greater than Comp off Credited date.!"));	
					exit(0);
				}
			}
			
			if($leave_category === 3){ // Check Sick leave Should not Future days
				if(date("Y-m-d",strtotime($to_date)) > date("Y-m-d")){
					echo json_encode(array('success' => false, 'message' => "Sick Leave should not be the Future date..!"));	
					exit(0);
				}
			}
			// IS EL SHOULD NOT ALLOW FULLDAY
			if((int)$is_el === 1 && ((int)$from_date_type !== 1 || (int)$to_date_type !== 1)) {
				echo json_encode(array('success' => false, 'message' => "This leave type $leave_description is only accept full day Leave"));
				exit(0);
			}
		}

		if($salary_start_date <= $from_date && $year_end_date >= $to_date){
			//SHIFT DATE AVAILABILITY TO CHECK FOR LEAVE DATES
			/*$shift_date_validate      = $this->shift_date_validate($employee_code,$from_date,$to_date);
			if($shift_date_validate){*/
			//PERMISISON REQUEST VALIDATE
			$other_req_validate   = $this->other_request_exist($employee_code,$prime_financial_id,$from_date,$to_date,$from_date_type,$to_date_type);
			if($other_req_validate){
				return true;
			}
			//}
		}else{
			echo json_encode(array('success' => false, 'message' => 'Please Check a Salary Start Date and End Date..!'));		
		}		
	}

    //CHECK A PERMISSION IN BEFORE SUBMIT
    public function check_permission_validation($post_data){
        $component_value     = $post_data["component_value"];
        $employee_code       = $post_data["employee_code"];
        $permission_date     = $post_data["permission_date"];
        $shift_name 	     = $post_data["shift_name"];
        $permission_type     = $post_data["permission_type"];
        $in_time             = $post_data["in_time"];
        $out_time            = $post_data["out_time"];
        $total_time          = $post_data["total_time"];
		$device_code         = $post_data["device_code"];

		$financial_info      = $this->get_leave_financial_details();
		$prime_financial_id  = $financial_info[0]->prime_leave_financial_year_id;

        //function for check a pending Shift Change Request request status
        $check_exist_shift_sts  = $this->check_exist_shift_sts($component_value,$employee_code,$permission_date);
        if($check_exist_shift_sts){
			//Check DATE Exist from LEAVE AND OD Entry (only for FULL DAY TYPE)
			$check_exist_leave_od  = $this->check_exist_leave_od($component_value,$prime_financial_id,$employee_code,$permission_date);

			if(!$check_exist_leave_od){
				echo json_encode(array('success' => false, 'message' => "Already Transaction Exist.! Please Cancel the Previous Transaction and try Again.!"));
           		exit(0);
			}else{
				if($in_time === "00:00" || $in_time === ""){
					echo json_encode(array('success' => false, 'message' => 'Intime should not be Empty!'));
				}else
				if($out_time === "00:00" || $out_time === ""){
					echo json_encode(array('success' => false, 'message' => 'Outtime Should not be Empty!'));
				}else
				if($in_time && $out_time && $shift_name){
					//FUNCTION FOR GET A SHIFT IN AND OUT TIME DR CODE
					$shift_master_rslt  = $this->shift_time_qry($shift_name);
					$from_time          = date("H:i",strtotime($shift_master_rslt[0]->from_time));
					$to_time            = date("H:i",strtotime($shift_master_rslt[0]->to_time));	
					/*if($from_time && $to_time){
						if(($from_time !== $in_time) && ($to_time !== $out_time)){
							echo json_encode(array('success' => false, 'message' => 'Permission Only Allow Shift Start or Shift End Time..'));
						}else{*/
							if((int)$permission_type === 4){
								$coff_permission_date   = date("Y-m-d",strtotime("-1 days",strtotime($permission_date)));
								//FUNCTION FOR GET TIME ENTRY COFF HOURS
								$coff_hrs_rslt          = $this->time_entry_coff_hrs($prime_financial_id,$employee_code,$coff_permission_date);
								$coff_hrs               = $coff_hrs_rslt[0]["coff_hours"];
								if(!$coff_hrs || $coff_hrs === "0"){
									echo json_encode(array('success' => false, 'message' => 'Coff Hours not Available Please Check Time Entry.!'));		
									exit(0);
								}else{
									//TIME ENTRY COFF HOURS BASED TOTAL HOURS VALIDATIONS CHECK
									$total_time_arr   = explode(":",$total_time);
									$total_hrs        = $total_time_arr[0]*60 + $total_time_arr[1];
									if($total_hrs > $coff_hrs){
										echo json_encode(array('success' => false, 'message' => 'Total Permission Hours should not Greater than Coff Hours.!'));
										exit(0);	
									}else{
										$in_time_count       = count(explode(":",$in_time));
										$out_time_count      = count(explode(":",$out_time));
										if((int)$in_time_count === 2){
											$in_time         = $in_time.":00";
										}
										if((int)$out_time_count === 2){
											$out_time        = $out_time.":00";
										}
										$in_date_time        = date("Y-m-d H:i:s",strtotime($permission_date." ".$in_time));
										$out_date_time       = date("Y-m-d H:i:s",strtotime($permission_date." ".$out_time));
										
										//TIME LOG MIN IN TIME GET
										//--- DON'T DELETE ----
										// $log_in_time_rslt    = $this->time_log_in_time($prime_financial_id,$employee_code,$permission_date,$device_code);
										$log_in_time_qry     = 'select punch_in as min_log_date,punch_out as max_log_date from cw_time_entry where cw_time_entry.employee_code = "'.$employee_code.'" and att_date = "'.$permission_date.'" and cw_time_entry.trans_status = 1';
										//echo $log_in_time_qry; die;
										$log_in_time_info    = $this->db->query("CALL sp_a_run ('SELECT','$log_in_time_qry')");
										$log_in_time_rslt    = $log_in_time_info->result_array();
										$log_in_time_info->next_result();

										$min_log_date_time   = "";
										if($log_in_time_rslt[0]["min_log_date"] !== "0000-00-00 00:00:00"){
											$min_log_date_time     = date('Y-m-d H:i:s', strtotime($log_in_time_rslt[0]["min_log_date"]));
										}
										//echo "BSK $out_date_time :: $min_log_date_time"; die;	
										//TIME LOG MIN IN TIME BASED VALIDATION
										if($min_log_date_time){
											if($in_date_time >= $min_log_date_time){
												echo json_encode(array('success' => false, 'message' => "In Date and Time should Lesser than or equal to Punch in Time ($min_log_date_time).!"));
												exit(0);	
											}else
											if($out_date_time >= $min_log_date_time){
												echo json_encode(array('success' => false, 'message' => "Out Date and Time should Lesser than or equal to Punch in Time ($min_log_date_time).!"));
												exit(0);
											}
										}
									} 
								}
							}
							
							//permission validation exist check
							return $this->permission_setting_check($component_value,$employee_code,$permission_date,$shift_name,$in_time,$out_time,$total_time,$permission_type);
					/* }
					}else{
						echo json_encode(array('success' => false, 'message' => 'Shift Time not Added to Shift Master.!'));				
					}*/		
				}
			}
        }else{
            echo json_encode(array('success' => false, 'message' => "Already Transaction Exist with the current Shift.! Please Cancel the Previous Transaction and try Again.!"));
            exit(0);
        }
    }

	//CHECK A MANUAL PUCH IN BEFORE SUBMIT
	public function shift_change_validation($post_data){
		$component_value          = $post_data["component_value"];
		$employee_code            = $post_data["employee_code"];
		$shift_date 	          = date("Y-m-d",strtotime($post_data["shift_date"]));
        $current_shift            = (int)$post_data["current_shift"];
        $change_shift             = (int)$post_data["change_shift"];

        //function for check a pending request status
        $check_exist_request_sts  = $this->check_exist_request_sts($component_value,$employee_code,$shift_date);
        if($check_exist_request_sts){
        	if($shift_date && $current_shift && $change_shift){
	        	if($current_shif === $change_shift){
	        		echo json_encode(array('success' => false, 'message' => "Don't Choose Same Shift Name.? Please Check it.!"));
					exit(0);
	       		}else{
	       			return true;
	       		}
	        }
        }else{
        	echo json_encode(array('success' => false, 'message' => "Already Transaction Exist with the current Shift.. Please Cancel the Previous Transaction and try Again.!"));
			exit(0);
        }
    }

	//CHECK A MANUAL PUCH IN BEFORE SUBMIT
	public function manual_punch_validation($post_data){
		$component_value     = $post_data["component_value"];
		$employee_code       = $post_data["employee_code"];
		$shift_date 	     = date("Y-m-d",strtotime($post_data["shift_date"]));
		$in_date 	         = date("Y-m-d",strtotime($post_data["in_date"]));
		$in_time             = $post_data["in_time"];
		$out_date 	         = date("Y-m-d",strtotime($post_data["out_date"]));
		$out_time            = $post_data["out_time"];
		$total_time          = $post_data["total_time"];
		$day_type            = (int)$post_data["day_type"];
		$mp_reason           = (int)$post_data["mp_reason"];
		$device_code         = $post_data["device_code"];
		$in_date_time        = date('Y-m-d H:i', strtotime($in_date.' '.$in_time));
		$out_date_time       = date('Y-m-d H:i', strtotime($out_date.' '.$out_time));
		$mp_treat_time_log   = $this->company_info[0]->mp_treat_as;
		
		//function for check a pending request status
        $check_exist_shift_sts  = $this->check_exist_shift_sts($component_value,$employee_code,$shift_date);
        if($check_exist_shift_sts){
			if($in_time === "00:00" || $in_time === ""){
				echo json_encode(array('success' => false, 'message' => 'In Time should not be Empty!'));
			}else
			if($out_time === "00:00" || $out_time === ""){
				echo json_encode(array('success' => false, 'message' => 'Out Time Should not be Empty!'));
			}else
			if($total_time === "00:00" || $total_time === ""){
				echo json_encode(array('success' => false, 'message' => 'total Time Should not be Empty!'));
				exit(0);
			}else{
				$next_date       = date('Y-m-d', strtotime('+1 day', strtotime($shift_date)));
				$prev_date       = date('Y-m-d', strtotime('-1 day', strtotime($shift_date)));				
				//THIS CHOOSE DATE USED FOR CHECK OUR OUT DATE IS TOMORROW OR NOT
				$choose_date     = date('Y-m-d', strtotime('+1 day', strtotime($in_date)));
				//FOR WE ONCE CHANGE A IN TIME OR OUT TIME NOT SECONDS ADDED SO STATICALLY ADD 
				$in_time_count   = count(explode(":",$in_time));
				$out_time_count  = count(explode(":",$out_time));
				if((int)$in_time_count === 2){
					$in_time     = $in_time.":00";
				}
				if((int)$out_time_count === 2){
					$out_time    = $out_time.":00";
				}

				if($in_date === $out_date){
					if($in_time >= $out_time){
						echo json_encode(array('success' => false, 'message' => 'Out Time should be Greater than In Time..!'));
						exit(0);
					}	
				}else
				if($in_date !== $out_date){
					if($in_time <= $out_time){
						echo json_encode(array('success' => false, 'message' => 'In Time should be Greater than Out Time..!'));
						exit(0);
					}
				}
				//check exist conditions from manual punch entry table
				$man_punch_check_qry   = 'SELECT COUNT(*) as count from cw_manual_punch_entry where employee_code = "'.$employee_code.'" and cw_manual_punch_entry.shift_date = "'.$shift_date.'" and leave_status in (1,2) and trans_status = 1';
				// and (day_type = "'.$day_type.'" or day_type = 1)
				$man_punch_check_info  = $this->db->query("CALL sp_a_run ('SELECT','$man_punch_check_qry')");
				$man_punch_check_rslt  = $man_punch_check_info->result();
				$man_punch_check_info->next_result();
				$mp_check_count        = (int)$man_punch_check_rslt[0]->count;
				if($mp_check_count){
					echo json_encode(array('success' => false, 'message' => 'Manual Punch Request Already Exist in the Same Date..!'));
					exit(0);
				}else{
					//this condition check only for forgot punch reason only
					if($this->config->item("db_name") === 'tcl_hrms' || $this->config->item("db_name") === 'tcl_dev'){
						if($mp_reason === 2){
							$process_month         = date("m-Y",strtotime($in_date));
							//DR CODE SALARY START DATE AND END DATE DETAILS GET
							$salary_start_end_info = $this->tos_sal_strt_end_info("3",$process_month); // 3 => Leave Entry
							if(count($salary_start_end_info)){
								$salary_start_date     = date("Y-m-d",strtotime($salary_start_end_info['salary_start_date']));
								$salary_end_date       = date("Y-m-d",strtotime($salary_start_end_info['salary_end_date']));
								$man_punch_check_qry   = 'SELECT COUNT(*) as count from cw_manual_punch_entry where employee_code = "'.$employee_code.'" and cw_manual_punch_entry.shift_date between "'.$salary_start_date.'" and "'.$salary_end_date.'" and leave_status in (1,2) and mp_reason = 2 and trans_status = 1';
								$man_punch_check_info  = $this->db->query("CALL sp_a_run ('SELECT','$man_punch_check_qry')");
								$man_punch_check_rslt  = $man_punch_check_info->result();
								$man_punch_check_info->next_result();
								$mp_check_count        = (int)$man_punch_check_rslt[0]->count;
								if($mp_check_count >= 3){
									echo json_encode(array('success' => false, 'message' => 'You Have Reached a Maximum Forgot Punch Request..Please Contact Admin..?'));
									exit(0);
								}
							}
						}
					}
				}
				//TIME LOG BASED MANUAL PUNCH
				if((int)$mp_treat_time_log === 1){
					if($this->config->item("db_name") !== 'rebar_hrms_db'){ //If multi inout
						//TIME LOG MIN AND MAX DATE AND TIME GET
						// GROUP BY cw_time_log.user_id,date_format(str_to_date(cw_time_log.log_date, "%Y-%m-%d %H:%i:%s"),"%Y-%m-%d")
						$time_log_date_qry    = 'select punch_in as min_log_date,punch_out as max_log_date from cw_time_entry where cw_time_entry.employee_code = "'.$employee_code.'" and att_date = "'.$in_date.'" and cw_time_entry.trans_status = 1';
						$time_log_date_info  = $this->db->query("CALL sp_a_run ('SELECT','$time_log_date_qry')");
						$time_log_date_rslt  = $time_log_date_info->result_array();
						$time_log_date_info->next_result();
						if(empty($time_log_date_rslt)){
							return true;
						}else{
							$min_log_date_time = "";
							$max_log_date_time = "";
							if($time_log_date_rslt[0]["min_log_date"] && $time_log_date_rslt[0]["min_log_date"] !== "0000-00-00 00:00:00" && $time_log_date_rslt[0]["min_log_date"] !== "1970-01-01 05:30:00" && $time_log_date_rslt[0]["min_log_date"] !== NULL){
								$min_log_date_time     = date('Y-m-d H:i', strtotime($time_log_date_rslt[0]["min_log_date"]));
							}

							if($time_log_date_rslt[0]["max_log_date"] && $time_log_date_rslt[0]["max_log_date"] !== "0000-00-00 00:00:00" && $time_log_date_rslt[0]["max_log_date"] !== "1970-01-01 05:30:00" && $time_log_date_rslt[0]["max_log_date"] !== NULL){
								$max_log_date_time     = date('Y-m-d H:i', strtotime($time_log_date_rslt[0]["max_log_date"]));
							}
							//TIME LOG IN AND OUT TIME BASED VALIDATIONS						
							if($min_log_date_time){
								if($in_date_time > $min_log_date_time){
									echo json_encode(array('success' => false, 'message' => 'In Time should be Lesser than Punch In Time..!'));
									exit(0);
								}
							}
							if($max_log_date_time){
								if($out_date_time < $max_log_date_time){
									echo json_encode(array('success' => false, 'message' => 'Out Time should be Greater than Punch Out Time..!'));
									exit(0);
								}	
							}
							return true;
						}
					}else{
						return true;
					}
				}else{
					$shift_time_qry    = 'select cw_shift_import.shift_name,cw_shift_import.shift_date as shift_date,cw_shift_master.from_time,cw_shift_master.to_time,cw_shift_master.first_half as first_half,cw_shift_master.second_half as second_half,cw_shift_master.shift_status,cw_shift_master.shift_start,cw_shift_master.shift_end,cw_shift_master.in_time as import_in_time,cw_shift_master.out_time as import_out_time,cw_shift_master.half_work_hour,cw_shift_master.full_work_hour from cw_shift_import inner join cw_shift_master on cw_shift_master.prime_shift_master_id = cw_shift_import.shift_name where cw_shift_import.employee_code = "'.$employee_code.'" and cw_shift_import.shift_date = "'.$shift_date.'" and cw_shift_import.trans_status = 1';
					$shift_time_info   = $this->db->query("CALL sp_a_run ('SELECT','$shift_time_qry')");
					$shift_time_result = $shift_time_info->result();
					$shift_time_info->next_result();
					$shift_date        = $shift_time_result[0]->shift_date;
					$today_shift_next  = date('Y-m-d', strtotime('+1 day', strtotime($shift_date)));
					$from_time         = $shift_time_result[0]->from_time;
					$to_time           = $shift_time_result[0]->to_time;
					$first_half        = $shift_time_result[0]->first_half;
					$second_half       = $shift_time_result[0]->second_half;
					$shift_status      = (int)$shift_time_result[0]->shift_status;
					$shift_start       = (int)$shift_time_result[0]->shift_start;
					$shift_end         = (int)$shift_time_result[0]->shift_end;
					$import_in_time    = $shift_time_result[0]->import_in_time;
					$import_out_time   = $shift_time_result[0]->import_out_time;
					$half_work_hour    = date('H:i:s', strtotime($shift_time_result[0]->half_work_hour));
					$full_work_hour    = date('H:i:s', strtotime($shift_time_result[0]->full_work_hour));
					$total_time        = date('H:i:s', strtotime($total_time));
					$shift_from_date   = date('Y-m-d H:i:s', strtotime($shift_date.' '.$from_time));
					$shift_to_date     = date('Y-m-d H:i:s', strtotime($shift_date.' '.$to_time));
					$shift_first_half  = date('Y-m-d H:i:s', strtotime($shift_date.' '.$first_half));
					$shift_second_half = date('Y-m-d H:i:s', strtotime($shift_date.' '.$second_half));
					$import_in_date    = date('Y-m-d H:i:s', strtotime($shift_date.' '.$import_in_time));
					$import_out_date   = date('Y-m-d H:i:s', strtotime($shift_date.' '.$import_out_time));
					$in_date_time      = date('Y-m-d H:i:s', strtotime($in_date.' '.$in_time));
					$out_date_time     = date('Y-m-d H:i:s', strtotime($out_date.' '.$out_time));

					if($shift_status === 1){
						if($shift_start === 3){
							$import_in_date   = date('Y-m-d H:i:s', strtotime($prev_date.' '.$import_in_time));
						}	
						if($shift_end === 2){
							$import_out_date  = date('Y-m-d H:i:s', strtotime($next_date.' '.$import_out_time));
						}	
					}else
					if($shift_status === 2){
						$shift_to_date         = date('Y-m-d H:i:s', strtotime($next_date.' '.$to_time));
						if($from_time > $first_half){
							$shift_first_half  = date('Y-m-d H:i:s', strtotime($next_date.' '.$first_half));
							$shift_second_half = date('Y-m-d H:i:s', strtotime($next_date.' '.$second_half));
						}
						if($shift_end === 2){
							$import_out_date   = date('Y-m-d H:i:s', strtotime($next_date.' '.$import_out_time));
						}	
					}else
					if($shift_status === 3){
						$shift_from_date       = date('Y-m-d H:i:s', strtotime($next_date.' '.$from_time));
						$shift_to_date         = date('Y-m-d H:i:s', strtotime($next_date.' '.$to_time));
						$shift_first_half      = date('Y-m-d H:i:s', strtotime($next_date.' '.$first_half));
						$shift_second_half     = date('Y-m-d H:i:s', strtotime($next_date.' '.$second_half));
						if($shift_start === 1){
							$import_in_date    = date('Y-m-d H:i:s', strtotime($shift_date.' '.$import_in_time));
						}	
						if($shift_end === 2){
							$import_out_date   = date('Y-m-d H:i:s', strtotime($next_date.' '.$import_out_time));
						}	
					}

					if($day_type === 1){
						if($shift_first_half <= $in_date_time || $import_in_date > $in_date_time){
							echo json_encode(array('success' => false, 'message' => 'Please Map Correct In Date or In Time..!!'));
							exit(0);
						}else
						if($shift_second_half >= $out_date_time || $import_out_date < $out_date_time){
							echo json_encode(array('success' => false, 'message' => 'Please Map to Correct Out Date or OutTime!'));
							exit(0);
						}else
						if($full_work_hour > $total_time){
							echo json_encode(array('success' => false, 'message' => 'Total Time should not Lesser than Full Day Work Hours..!!'));
							exit(0);
						}else{
							return true;
						}
					}else
					if($day_type === 2){

						if($shift_first_half <= $in_date_time || $import_in_date > $in_date_time){
							echo json_encode(array('success' => false, 'message' => 'Please Check to Correct In Date or Time!'));
							exit(0);
						}else
						if($shift_form_date >= $out_date_time || $shift_to_date <= $out_date_time || $import_out_date < $out_date_time){
							echo json_encode(array('success' => false, 'message' => 'Please Check to Correct Out Date or Time!'));
							exit(0);
						}else
						if($half_work_hour > $total_time){
							echo json_encode(array('success' => false, 'message' => 'Total Time should not Lesser than Half Day Work Hours..!!'));
							exit(0);
						}else{
							return true;
						}
					}else{
						if($shift_from_date >= $in_date_time || $shift_to_date <= $in_date_time || $import_in_date > $in_date_time){
							echo json_encode(array('success' => false, 'message' => 'Please Check to Correct In Date or Time!'));
							exit(0);
						}else
						if($shift_second_half >= $out_date_time || $import_out_date < $out_date_time){
							echo json_encode(array('success' => false, 'message' => 'Please Check to Correct Out Date or Time!'));
							exit(0);
						}else
						if($half_work_hour > $total_time){
							echo json_encode(array('success' => false, 'message' => 'Total Time should not Lesser than Half Day Work Hours..!!'));
							exit(0);
						}else{
							return true;
						}	
					}
				}	
			}
		}else{
			echo json_encode(array('success' => false, 'message' => "Already Transaction Exist with the current Shift.! Please Cancel the Previous Transaction and try Again.!"));
			exit(0);
		}
	}
	// FUNCTION FOR PERMISSION ENTRY TYPE
	public function permission_entry($post_data,$form_id,$prime_financial_id){
		$leave_financial_info          = $this->get_leave_financial_details();
		$prime_leave_financial_year_id = $leave_financial_info[0]->prime_leave_financial_year_id;
		$approval_insert_key           = "";
		$approval_insert_value         = "";
		$approval_update_qry           = "";
		$print_type_id                 = "";
		$created_on                    = date("Y-m-d H:i:s");    
		foreach ($post_data as $key => $value) {
			if($key === "request_date"){
				$key = "applied_on";
			}
			if($key === "from_date"){
				$from_date = $value;
			}
			if($key === "to_date"){
				$to_date = $value;
			}
			if($key === "first_level_approval"){
				$current_control = $value;
			}
			if($key === "request_type"){
				$request_type = $value;
			}
			if($key === "leave_approve_type"){
				$leave_approve_type = $value;
			}
			if($key === "second_level_approval"){
				$second_level_approval = $value;
			}

			$approval_insert_key     .= $key.",";
			$approval_insert_value   .= '"'.$value.'",';
			$approval_update_qry   .= $key.' = "'.$value.'",';		
		}
	
		if((int)$request_type === 4 || (int)$request_type === 5){
			$component_value  = $post_data["component_value"];
			$employee_code    = $post_data["employee_code"];
			$permission_date  = $post_data["permission_date"];
			$shift_name 	  = $post_data["shift_name"];
			$permission_type  = $post_data["permission_type"];
			$from_date_type   = $post_data["from_date_type"];
			$to_date_type 	  = $post_data["to_date_type"];
			$in_time          = $post_data["in_time"];
			$out_time         = $post_data["out_time"];
			$total_time       = $post_data["total_time"];
			$leave_status     = $post_data["leave_status"];
			$total_time_arr   = explode(':', $total_time);
    		$total_minute     = round(($total_time_arr[0]*60) + ($total_time_arr[1]));

			$permission_entry_value = '("'.$component_value.'","'.$employee_code.'","'.$prime_leave_financial_year_id.'","'.$permission_date.'","'.$shift_name.'","'.$permission_type.'","'.$in_time.'","'.$out_time.'","'.$total_time.'","'.$total_minute.'","'.$form_id.'","'.$leave_status.'","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'")';
			
			$request_permission_insert_qry 	  = "INSERT into cw_permission_entry (component_value,employee_code,financial_setting_id,permission_date,shift_name,permission_type,in_time,out_time,total_time,total_minute,prime_request_id,leave_status,trans_created_by,trans_created_date) values $permission_entry_value";
			$request_permission_insert_info   = $this->db->query("CALL sp_a_run ('INSERT','$request_permission_insert_qry')");
			$request_permission_insert_result = $request_permission_insert_info->result();
			$request_permission_insert_info->next_result();

			if(!empty($request_permission_insert_result)){
				$approval_insert_key     .= "current_control,prime_request_id,financial_setting_id,trans_created_by,trans_created_date";
				$approval_insert_value   .= '"'.$current_control.'","'.$form_id.'","'.$prime_leave_financial_year_id.'","'.$this->logged_id.'","'.$created_on.'"';

				$approval_insert_query    = "insert into cw_approval (".$approval_insert_key.") values (".$approval_insert_value.")";
				$approval_insert_info     = $this->db->query("CALL sp_a_run ('INSERT','$approval_insert_query')");
				$approval_insert_result   = $approval_insert_info->result();
				$approval_insert_info->next_result();
			}
			$employee_detail_qry  		  = 'select prime_employees_id,first_level_approval,second_level_approval from cw_employees where employee_code = "'.$employee_code.'" and trans_status = 1';
			$employee_detail_info  	      = $this->db->query("CALL sp_a_run ('SELECT','$employee_detail_qry')");
			$employee_detail_result       = $employee_detail_info->result();
			$employee_detail_info->next_result();
			$view_id 					  = $employee_detail_result[0]->prime_employees_id;
			$first_level_approval_code	  = $employee_detail_result[0]->first_level_approval;
			$second_level_approval_code	  = $employee_detail_result[0]->second_level_approval;

			$first_approval_qry  		  = 'select company_email_id from cw_employees where employee_code = "'.$first_level_approval_code.'" and trans_status = 1';
			$first_approval_info  	      = $this->db->query("CALL sp_a_run ('SELECT','$first_approval_qry')");
			$first_approval_result        = $first_approval_info->result();
			$first_approval_info->next_result();
			$first_approval_mail 		  = $first_approval_result[0]->company_email_id;

			$second_approval_qry  		  = 'select company_email_id from cw_employees where employee_code = "'.$second_level_approval_code.'" and trans_status = 1';
			$second_approval_info  	      = $this->db->query("CALL sp_a_run ('SELECT','$second_approval_qry')");
			$second_approval_result  	  = $second_approval_info->result();
			$second_approval_info->next_result();
			$second_approval_mail 		  = $second_approval_result[0]->company_email_id;

			$print_type_id = 27;
			if((int)$leave_approve_type === 1){
				return $this->send_mail($print_type_id,$form_id,$first_approval_mail,$second_approval_mail);
			}else
			if((int)$leave_approve_type === 2){
				return $this->send_mail($print_type_id,$form_id,$first_approval_mail,$second_approval_mail);
			}else
			if((int)$leave_approve_type === 3){
				return $this->send_mail($print_type_id,$form_id,$first_approval_mail,"");
			}else
			if((int)$leave_approve_type === 4){
				return $this->send_mail($print_type_id,$form_id,"",$second_approval_mail);
			}		
		}		
	}
	// FUNCTION FOR SHIFT CHANGE TYPE
	public function shift_change_entry($post_data,$form_id,$prime_financial_id){
		$leave_financial_info          = $this->get_leave_financial_details();
		$prime_leave_financial_year_id = $leave_financial_info[0]->prime_leave_financial_year_id;
		
		$approval_insert_key      = "";
		$approval_insert_value    = "";
		$approval_update_qry      = "";
		$created_on               = date("Y-m-d H:i:s");    

		foreach ($post_data as $key => $value) {
			if($key === "request_date"){
				$key        = "applied_on";
			}
			if($key === "shift_date"){
				$shift_date = $value;
			}
			if($key === "current_shift"){
				$current_shift = $value;
			}
			if($key === "change_shift"){
				$change_shift = $value;
			}
			if($key === "request_type"){
				$request_type = $value;
			}
			if($key === "leave_approve_type"){
				$leave_approve_type = $value;
			}
			if($key === "first_level_approval"){
				$current_control = $value;
			}
			if($key === "second_level_approval"){
				$second_level_approval = $value;
			}

			$approval_insert_key     .= $key.",";
			$approval_insert_value   .= '"'.$value.'",';
			$approval_update_qry     .= $key.' = "'.$value.'",';	
		}
		$approval_insert_key     .= "current_control,prime_request_id,financial_setting_id,trans_created_by,trans_created_date";
		$approval_insert_value   .= '"'.$current_control.'","'.$form_id.'","'.$prime_leave_financial_year_id.'","'.$this->logged_id.'","'.$created_on.'"';

		$approval_insert_query = "insert into cw_approval (".$approval_insert_key.") values (".$approval_insert_value.")";
		$approval_insert_info  = $this->db->query("CALL sp_a_run ('INSERT','$approval_insert_query')");
		$approval_insert_result  = $approval_insert_info->result();
		$approval_insert_info->next_result();

		$employee_detail_qry  		 = 'select prime_employees_id,first_level_approval,second_level_approval from cw_employees where employee_code = "'.$employee_code.'" and trans_status = 1';
		$employee_detail_info  	     = $this->db->query("CALL sp_a_run ('SELECT','$employee_detail_qry')");
		$employee_detail_result      = $employee_detail_info->result();
		$employee_detail_info->next_result();
		$view_id 					 = $employee_detail_result[0]->prime_employees_id;
		$first_level_approval_code	 = $employee_detail_result[0]->first_level_approval;
		$second_level_approval_code	 = $employee_detail_result[0]->second_level_approval;

		$first_approval_qry  		 = 'select company_email_id from cw_employees where employee_code = "'.$first_level_approval_code.'" and trans_status = 1';
		$first_approval_info  	     = $this->db->query("CALL sp_a_run ('SELECT','$first_approval_qry')");
		$first_approval_result       = $first_approval_info->result();
		$first_approval_info->next_result();
		$first_approval_mail 		 = $first_approval_result[0]->company_email_id;

		$second_approval_qry  		 = 'select company_email_id from cw_employees where employee_code = "'.$second_level_approval_code.'" and trans_status = 1';
		$second_approval_info  	     = $this->db->query("CALL sp_a_run ('SELECT','$second_approval_qry')");
		$second_approval_result  	 = $second_approval_info->result();
		$second_approval_info->next_result();
		$second_approval_mail 		 = $second_approval_result[0]->company_email_id;

		$print_type_id               = 39;	
		if((int)$leave_approve_type === 1){
			return $this->send_mail($print_type_id,$form_id,$first_approval_mail,$second_approval_mail);
		}else
		if((int)$leave_approve_type === 2){
			return $this->send_mail($print_type_id,$form_id,$first_approval_mail,$second_approval_mail);
		}else
		if((int)$leave_approve_type === 3){
			return $this->send_mail($print_type_id,$form_id,$first_approval_mail,"");
		}else
		if((int)$leave_approve_type === 4){
			return $this->send_mail($print_type_id,$form_id,"",$second_approval_mail);
		}
	
	}
	// FUNCTION FOR MANUAL PUNCH TYPE
	public function manual_punch_entry($post_data,$form_id,$prime_financial_id){
		$leave_financial_info            = $this->get_leave_financial_details();
		$prime_leave_financial_year_id   = $leave_financial_info[0]->prime_leave_financial_year_id;
		$approval_insert_key             = "";
		$approval_insert_value           = "";
		$approval_update_qry             = "";
		$created_on                      = date("Y-m-d H:i:s");          
		foreach ($post_data as $key => $value) {
			if($key === "request_date"){
				$key  = "applied_on";
			}
			if($key === "component_value"){
				$component_value = $value;
			}
			if($key === "employee_code"){
				$employee_code = $value;
			}
			if($key === "shift_date"){
				$shift_date  = $value;
			}
			if($key === "in_date"){
				$in_date     = $value;
			}
			if($key === "out_date"){
				$out_date = $value;
			}
			if($key === "shift_name"){
				$shift_name = $value;
			}
			if($key === "day_type"){
				$day_type = $value;
			}
			if($key === "in_time"){
				$in_time = $value;
			}
			if($key === "out_time"){
				$out_time = $value;
			}
			if($key === "total_time"){
				$total_time = $value;
			}
			if($key === "leave_status"){
				$leave_status = $value;
			}
			if($key === "mp_reason"){
				$mp_reason = $value;
			}
			if($key === "request_type"){
				$request_type = $value;
			}
			if($key === "leave_approve_type"){
				$leave_approve_type = $value;
			}
			if($key === "first_level_approval"){
				$current_control = $value;
			}
			if($key === "second_level_approval"){
				$second_level_approval = $value;
			}
			$approval_insert_key     .= $key.",";
			$approval_insert_value   .= '"'.$value.'",';
			$approval_update_qry     .= $key.' = "'.$value.'",';	
		}
		//Manual punch insert query
		$manual_punch_val      = '("'.$form_id.'","'.$prime_financial_id.'","'.$component_value.'",'.'"'.$employee_code.'",'.'"'.$shift_name.'",'.'"'.$shift_date.'",'.'"'.$in_date.'",'.'"'.$out_date.'",'.'"'.$in_time.'",'.'"'.$out_time.'",'.'"'.$total_time.'",'.'"'.$day_type.'","'.$leave_status.'","'.$mp_reason.'",'.'"'.$this->logged_id.'",'.'"'.$created_on.'")';

		$manual_punch_ins_qry  = "INSERT into cw_manual_punch_entry (prime_request_id,financial_setting_id,component_value,employee_code,shift_name,shift_date,in_date,out_date,in_time,out_time,total_time,day_type,leave_status,mp_reason,trans_created_by,trans_created_date) values $manual_punch_val";
		$manual_punch_ins_info = $this->db->query("CALL sp_a_run ('INSERT','$manual_punch_ins_qry')");
		$manual_punch_ins_rslt = $manual_punch_ins_info->result();
		$manual_punch_ins_info->next_result();

		if(!empty($manual_punch_ins_rslt)){
			$approval_insert_key     .= "current_control,prime_request_id,financial_setting_id,trans_created_by,trans_created_date";
			$approval_insert_value   .= '"'.$current_control.'","'.$form_id.'","'.$prime_leave_financial_year_id.'","'.$this->logged_id.'","'.$created_on.'"';

			$approval_insert_query = "insert into cw_approval (".$approval_insert_key.") values (".$approval_insert_value.")";
			$approval_insert_info  = $this->db->query("CALL sp_a_run ('INSERT','$approval_insert_query')");
			$approval_insert_result  = $approval_insert_info->result();
			$approval_insert_info->next_result();
		}

		$employee_detail_qry  		 = 'select prime_employees_id,first_level_approval,second_level_approval from cw_employees where employee_code = "'.$employee_code.'" and trans_status = 1';
		$employee_detail_info  	     = $this->db->query("CALL sp_a_run ('SELECT','$employee_detail_qry')");
		$employee_detail_result      = $employee_detail_info->result();
		$employee_detail_info->next_result();
		$view_id 					 = $employee_detail_result[0]->prime_employees_id;
		$first_level_approval_code	 = $employee_detail_result[0]->first_level_approval;
		$second_level_approval_code	 = $employee_detail_result[0]->second_level_approval;

		$first_approval_qry  		 = 'select company_email_id from cw_employees where employee_code = "'.$first_level_approval_code.'" and trans_status = 1';
		$first_approval_info  	     = $this->db->query("CALL sp_a_run ('SELECT','$first_approval_qry')");
		$first_approval_result       = $first_approval_info->result();
		$first_approval_info->next_result();
		$first_approval_mail 		 = $first_approval_result[0]->company_email_id;

		$second_approval_qry  		 = 'select company_email_id from cw_employees where employee_code = "'.$second_level_approval_code.'" and trans_status = 1';
		$second_approval_info  	     = $this->db->query("CALL sp_a_run ('SELECT','$second_approval_qry')");
		$second_approval_result  	 = $second_approval_info->result();
		$second_approval_info->next_result();
		$second_approval_mail 		 = $second_approval_result[0]->company_email_id;

		$print_type_id               = 45;
		if((int)$leave_approve_type === 1){
			return $this->send_mail($print_type_id,$form_id,$first_approval_mail,$second_approval_mail);
		}else
		if((int)$leave_approve_type === 2){
			return $this->send_mail($print_type_id,$form_id,$first_approval_mail,$second_approval_mail);
		}else
		if((int)$leave_approve_type === 3){
			return $this->send_mail($print_type_id,$form_id,$first_approval_mail,"");
		}else
		if((int)$leave_approve_type === 4){
			return $this->send_mail($print_type_id,$form_id,"",$second_approval_mail);
		}
	}
	//LEAVE ENTRY FUNCTION
	public function leave_entry($post_data,$form_id,$prime_financial_id){
		$leave_financial_info          = $this->get_leave_financial_details();
		$prime_leave_financial_year_id = $leave_financial_info[0]->prime_leave_financial_year_id;
		$approval_insert_key           = "";
		$approval_insert_value         = "";
		$approval_update_qry           = "";
		$print_type_id                 = "";
		$created_on                    = date("Y-m-d H:i:s");          
		foreach ($post_data as $key => $value){
			if($key === "employee_code"){
				$employee_code = $value;
			}
			if($key === "request_date"){
				$key = "applied_on";
			}
			if($key === "from_date"){
				$from_date = $value;
			}
			if($key === "to_date"){
				$to_date = $value;
			}
			if($key === "first_level_approval"){
				$current_control = $value;
			}
			if($key === "request_type"){
				$request_type = $value;
			}
			if($key === "leave_approve_type"){
				$leave_approve_type = $value;
			}
			if($key === "second_level_approval"){
				$second_level_approval = $value;
			}
			if($key !== "no_of_days"){
				$approval_insert_key     .= $key.",";
				$approval_insert_value   .= '"'.$value.'",';
				$approval_update_qry   .= $key.' = "'.$value.'",';
			}			
		}
		$employee_detail_qry  		 = 'select prime_employees_id,first_level_approval,second_level_approval from cw_employees where employee_code = "'.$employee_code.'" and trans_status = 1';
		$employee_detail_info  	     = $this->db->query("CALL sp_a_run ('SELECT','$employee_detail_qry')");
		$employee_detail_result      = $employee_detail_info->result();
		$employee_detail_info->next_result();
		$view_id 					 = $employee_detail_result[0]->prime_employees_id;
		$first_level_approval_code	 = $employee_detail_result[0]->first_level_approval;
		$second_level_approval_code	 = $employee_detail_result[0]->second_level_approval;

		$first_approval_qry  		 = 'select company_email_id from cw_employees where employee_code = "'.$first_level_approval_code.'" and trans_status = 1';
		$first_approval_info  	     = $this->db->query("CALL sp_a_run ('SELECT','$first_approval_qry')");
		$first_approval_result       = $first_approval_info->result();
		$first_approval_info->next_result();
		$first_approval_mail 		 = $first_approval_result[0]->company_email_id;

		$second_approval_qry  		 = 'select company_email_id from cw_employees where employee_code = "'.$second_level_approval_code.'" and trans_status = 1';
		$second_approval_info  	     = $this->db->query("CALL sp_a_run ('SELECT','$second_approval_qry')");
		$second_approval_result  	 = $second_approval_info->result();
		$second_approval_info->next_result();
		$second_approval_mail 		 = $second_approval_result[0]->company_email_id;
		
		$from_date_diff  = strtotime($from_date);
		$to_date_diff    = strtotime($to_date);
		$datediff        = $to_date_diff - $from_date_diff;
		$no_of_days      = round($datediff / (60 * 60 * 24));	
		if((int)$request_type === 1 || (int)$request_type === 2 || (int)$request_type === 3 || (int)$request_type === 8){
			$employee_code   = $post_data["employee_code"];
			$from_date_type  = $post_data["from_date_type"];
			$to_date_type 	 = $post_data["to_date_type"];
			$component_value = $post_data["component_value"];
			$leave_type      = $post_data["leave_type"];
			$from_date       = $post_data["from_date"];
			$to_date         = $post_data["to_date"];
			$startTimeStamp  = strtotime($from_date);
			$endTimeStamp    = strtotime($to_date);
			$timeDiff        = abs($endTimeStamp - $startTimeStamp);
			$numberDays      = $timeDiff/86400;  // 86400 seconds in one day
			// and you might want to convert to integer
			$numberDays      = intval($numberDays);
			$numberDays      = (int)$numberDays + 1;
			$date_range      = $this->getDatesFromRange($from_date, $to_date);
			$get_year        = date('Y',strtotime($from_date));

			//FOR MAIL FUNCTION
			$employee_detail_qry  		 = 'select prime_employees_id,first_level_approval,second_level_approval from cw_employees where employee_code = "'.$employee_code.'" and trans_status = 1';
			$employee_detail_info  	     = $this->db->query("CALL sp_a_run ('SELECT','$employee_detail_qry')");
			$employee_detail_result      = $employee_detail_info->result();
			$employee_detail_info->next_result();
			$view_id 					 = $employee_detail_result[0]->prime_employees_id;
			$first_level_approval_code	 = $employee_detail_result[0]->first_level_approval;
			$second_level_approval_code	 = $employee_detail_result[0]->second_level_approval;

			$first_approval_qry  		 = 'select company_email_id from cw_employees where employee_code = "'.$first_level_approval_code.'" and trans_status = 1';
			$first_approval_info  	     = $this->db->query("CALL sp_a_run ('SELECT','$first_approval_qry')");
			$first_approval_result       = $first_approval_info->result();
			$first_approval_info->next_result();
			$first_approval_mail 		 = $first_approval_result[0]->company_email_id;

			$second_approval_qry  		 = 'select company_email_id from cw_employees where employee_code = "'.$second_level_approval_code.'" and trans_status = 1';
			$second_approval_info  	     = $this->db->query("CALL sp_a_run ('SELECT','$second_approval_qry')");
			$second_approval_result  	 = $second_approval_info->result();
			$second_approval_info->next_result();
			$second_approval_mail 		 = $second_approval_result[0]->company_email_id;

			//for Get Leave Creation
			$leave_creation_qry    = 'SELECT count(*) as creation_count,leave_opening,intervening_holidays,intervening_type,leave_name,coff,coff_late from cw_leave_creation where cw_leave_creation.trans_status = 1 and prime_leave_creation_id = "'.$leave_type.'"';
			$leave_creation_info   = $this->db->query("CALL sp_a_run ('SELECT','$leave_creation_qry')");
			$leave_creation_result = $leave_creation_info->result();
			$leave_creation_info->next_result();
			$leave_opening         = $leave_creation_result[0]->leave_opening;	
			$intervening_holidays  = $leave_creation_result[0]->intervening_holidays;
			$intervening_type      = explode(",",$leave_creation_result[0]->intervening_type);
			$leave_name  		   = $leave_creation_result[0]->leave_name;
			$leave_name 		   = strtolower($leave_name);
			$creation_count 	   = $leave_creation_result[0]->creation_count;
			$coff 	               = $leave_creation_result[0]->coff;
			$coff_late 	           = $leave_creation_result[0]->coff_late;
			$pending_column 	   = "pending_".$leave_name;
			/*if((int)$coff_late === 1){ // For Coff Late created for Rebar
				if(($from_date === $to_date) && $from_date_type === 1 && $to_date_type === 1){
					$this->check_coff_late($employee_code,$from_date);
				}else{
					echo json_encode(array('success' => FALSE, 'message' => "Coff Late will be available for the Next Day first Half only.."));
					exit(0);
				}				
			}*/
			//SELECT QUERY FOR CHECK A GENENRAL SETTING PARAMETER BASED TYPE
			$param_based_type_qry  = 'SELECT parameter_type,based_on,check_parameter FROM cw_general_setting inner join cw_parameter_type on cw_parameter_type.prime_parameter_type_id = cw_general_setting.entry_parameter_type WHERE cw_general_setting.trans_status = 1';
			$param_based_type_info = $this->db->query("CALL sp_a_run ('SELECT','$param_based_type_qry')");
			$param_based_type_rslt = $param_based_type_info->result_array();
			$param_based_type_info->next_result();
			// print_r($param_based_type_rslt); die;
			// $param_based_type_arr  = array_reduce($param_based_type_rslt, function($result, $arr){			
		    // $result[$arr['parameter_type']] = $arr['based_on'];
		    // return $result;
			// }, array());


			$param_based_type_arr = array();
			$check_parameter_arr  = array();
			foreach ($param_based_type_rslt as $arr) {
				$param_based_type_arr[$arr['parameter_type']] = $arr['based_on'];
				$check_parameter_arr[$arr['parameter_type']]  = $arr['check_parameter'];
			}
			$week_off_entry        = (int)$param_based_type_arr['Weekly off Entry'];	
			$holiday_entry         = (int)$param_based_type_arr['Holiday Entry'];	
			$leave_entry           = (int)$param_based_type_arr['Leave Entry'];
			//CONDITION FOR CHECK A HOLIDAY DATE FOR PARAMETER TYPE BASED ON
			if($holiday_entry === 2){
				$holid_component_query  = 'SELECT pick_table,pick_list,components,label_name FROM cw_general_setting inner join cw_form_setting on cw_form_setting.prime_form_id = cw_general_setting.components WHERE entry_parameter_type = 2 and cw_general_setting.trans_status = 1';
				$holid_component_info   = $this->db->query("CALL sp_a_run ('SELECT','$holid_component_query')");
				$holid_component_result = $holid_component_info->result();
				$holid_component_info->next_result();	
			
				$holid_pick_list       = $holid_component_result[0]->pick_list;
				// $holid_pick_table = $holid_component_result[0]->pick_table;
				// $holid_components = $holid_component_result[0]->components;
				$holid_pick_list_val   = explode(",",$holid_pick_list);
				$holid_pick_list_val_1 = $holid_pick_list_val[0];
				$holid_pick_list_val_2 = $holid_pick_list_val[1];
				$holid_label_name      = $holid_component_result[0]->label_name;
				//$holid_comp_value    = $this->emp_pick_arr[$employee_code][$holid_label_name];
				$emp_pick_arr          = $this->get_emp_data();
				$holid_comp_value      = $emp_pick_arr[$employee_code][$holid_label_name];				
				//for Get Hollidays
				$holiday_qry       = 'select cw_holiday_entry_holiday_data.holiday_date from cw_holiday_entry inner join cw_holiday_entry_holiday_data on cw_holiday_entry_holiday_data.prime_holiday_entry_id = cw_holiday_entry.prime_holiday_entry_id where FIND_IN_SET("'.$holid_comp_value.'", cw_holiday_entry_holiday_data.component_value) and cw_holiday_entry.holiday_year = "'.$get_year.'" and cw_holiday_entry.trans_status = 1 and cw_holiday_entry_holiday_data.trans_status = 1';
				$holiday_info      = $this->db->query("CALL sp_a_run ('SELECT','$holiday_qry')");
				$holiday_result    = $holiday_info->result_array();
				$holiday_info->next_result();
			
				$holiday_result    = array_reduce($holiday_result, function($result, $arr){			
				    $result[$arr['holiday_date']] = $arr;
				    return $result;
				}, array());
				$valid_required  = (int)$check_parameter_arr['Weekly off Entry'];
				if($valid_required === 1){
					if($holiday_result[$from_date]){
						echo json_encode(array('success' => FALSE, 'message' => "Requested Date is Holiday,Request Not accepted...!"));
						exit(0);
					}
				}
			}
			
			//CONDITION FOR CHECK A WEEKOFF DATE FOR PARAMETER TYPE BASED ON
			if($week_off_entry === 1){
				$check_weekoff_qry   = 'SELECT employee_code,weekoff_date,weekoff_type from cw_weekoff_import WHERE employee_code = "'. $employee_code .'" and weekoff_date >= "'.$from_date.'" and weekoff_date <= "'.$to_date.'" and financial_setting_id = '.$prime_financial_id.' and trans_status = 1';
				$check_weekoff_info   = $this->db->query("CALL sp_a_run ('SELECT','$check_weekoff_qry')");
				$check_weekoff_rlst   = $check_weekoff_info->result_array();
				$check_weekoff_info->next_result();

				$weekoff_result       = array_reduce($check_weekoff_rlst, function($result, $arr){			
				    $result[$arr['employee_code']][$arr['weekoff_date']] = $arr['weekoff_type'];
				    return $result;
				}, array());
				$valid_required  = (int)$check_parameter_arr['Weekly off Entry'];
				if($valid_required === 1){
					if($holiday_result[$from_date]){
						echo json_encode(array('success' => FALSE, 'message' => "Requested Date is Week off,Request Not accepted...!"));
						exit(0);
					}
				}
			}else
			if($week_off_entry === 2){
				$week_component_query  = 'SELECT pick_table,pick_list,components,label_name FROM cw_general_setting inner join cw_form_setting on cw_form_setting.prime_form_id = cw_general_setting.components WHERE entry_parameter_type = 1 and cw_general_setting.trans_status = 1';
				$week_component_info   = $this->db->query("CALL sp_a_run ('SELECT','$week_component_query')");
				$week_component_result = $week_component_info->result();
				$week_component_info->next_result();		
				$week_pick_list   = $week_component_result[0]->pick_list;
				$week_pick_list_val   = explode(",",$week_pick_list);
				$week_pick_list_val_1 = $week_pick_list_val[0];
				$week_pick_list_val_2 = $week_pick_list_val[1];

				$week_label_name       = $week_component_result[0]->label_name;
				//$week_comp_value       = $this->emp_pick_arr[$employee_code][$week_label_name];
				$emp_pick_arr          = $this->get_emp_data();
				$week_comp_value       = $emp_pick_arr[$employee_code][$week_label_name];
				/* Weekoff - START */
				$weekoff_qry = 'select cw_weekoff_entry_weekoff_days_details.weekday,cw_weekoff_entry_weekoff_days_details.first_week,cw_weekoff_entry_weekoff_days_details.second_week,cw_weekoff_entry_weekoff_days_details.third_week,cw_weekoff_entry_weekoff_days_details.fourth_week,cw_weekoff_entry_weekoff_days_details.fifth_week from cw_weekoff_entry inner join cw_weekoff_entry_weekoff_days_details on cw_weekoff_entry_weekoff_days_details.prime_weekoff_entry_id = cw_weekoff_entry.prime_weekoff_entry_id where FIND_IN_SET("'.$week_comp_value.'", cw_weekoff_entry.component_value) and cw_weekoff_entry.from_date <= "'.$from_date.'" AND cw_weekoff_entry.to_date >= "'.$to_date.'" and cw_weekoff_entry.trans_status = 1 and cw_weekoff_entry_weekoff_days_details.trans_status = 1';
				$weekoff_info   = $this->db->query("CALL sp_a_run ('SELECT','$weekoff_qry')");
				$weekoff_result    = $weekoff_info->result_array();
				$weekoff_info->next_result();

				$weekoff_result = array_reduce($weekoff_result, function($result, $arr){			
				$result[$arr['weekday']] = $arr;
				    return $result;
				}, array());
				$valid_required  = (int)$check_parameter_arr['Weekly off Entry'];
				if($valid_required === 1){
					if($holiday_result[$from_date]){
						echo json_encode(array('success' => FALSE, 'message' => "Requested Date is Week off,Request Not accepted...!"));
						exit(0);
					}
				}
				/* Weekoff - END */
				$days_arr = array("sun"=>1,"mon"=>2,"tue"=>3,"wed"=>4,"thu"=>5,"fri"=>6,"sat"=>7);
				$week_arr = array(1=>"first_week",2=>"second_week",3=>"third_week",4=>"fourth_week",5=>"fifth_week");
			}
			$from_date_count  = 0;
			$to_date_count    = 0;
			if((int)$request_type === 1){
				if(!$leave_balance){
					$leave_balance =10;
				}
				if((int)$intervening_holidays === 1 && in_array("1",$intervening_type)){
					//Check before from date
					for($j=1;$j<=(int)$leave_balance;$j++){
						$date          = new DateTime($from_date);
						$date->modify("-$j day");
						$check_prev    = $date->format("Y-m-d");
						//WEEKOFF DATE CHECK
						if($week_off_entry === 1){
							$weekoff_value = (int)$weekoff_result[$employee_code][$check_prev];		
						}else
						if($week_off_entry === 2){
							$get_day       = strtolower(date('D',strtotime($check_prev)));
							$day           = $days_arr[$get_day];
							$week_no       = $this->weekOfMonth(strtotime($check_prev)); 
							$week          = $week_arr[$week_no];
							$weekoff_value = $weekoff_result[$day][$week];			
						}
						//HOLIDAY DATE CHECK
						if($holiday_entry === 2){
							$prev_holiday  = $holiday_result[$check_prev]['holiday_date'];
						}	
						if($prev_holiday ||  $weekoff_value){
							$from_date_count = $from_date_count + 1;
							if($from_date_count){
								$leave_entry_value .= '("'.$form_id.'","'.$prime_leave_financial_year_id.'","'.$component_value.'",'.'"'.$employee_code.'",'.'"'.$check_prev.'",'.'"'.$leave_type.'",'.'"1",'.'"1",'.'"1",'.'"'.$this->logged_id.'",'.'"'.date("Y-m-d H:i:s").'"),';
							}					
						}else{
							break;
						}									
					}
				}
				$end_key       = end(array_keys($date_range));
				$leave_count   = 0;
				$total_leave   = 0;
				foreach ($date_range as $key => $common_date){
					//WEEKOFF DATE CHECK
					if($week_off_entry === 1){
						$weekoff_value      = (int)$weekoff_result[$employee_code][$common_date];		
					}else
					if($week_off_entry === 2){
						$get_day            = strtolower(date('D',strtotime($common_date)));
						//Check weekoff day exist
						$day                = $days_arr[$get_day];
						$week_no            = $this->weekOfMonth(strtotime($common_date)); 
						$week               = $week_arr[$week_no];
						$weekoff_value      = $weekoff_result[$day][$week];	
					}
					//HOLIDAY DATE CHECK
					if($holiday_entry === 2){
						$get_common_holiday = $holiday_result[$common_date]['holiday_date'];
					}	
					if($key === 0){
						if((int)$from_date_type === 1){
							$leave_count = 1.00;
						}else
						if((int)$from_date_type === 2 || (int)$from_date_type === 3){
							$leave_count = 0.50;
						}
						$date_type       = $from_date_type;
					}else
					if($key === $end_key){						
						if((int)$to_date_type === 1){
							$leave_count = 1.00;
						}else
						if((int)$to_date_type === 2 || (int)$to_date_type === 3){
							$leave_count = 0.50;
						}
						$date_type       = $to_date_type;
					}else{
						
						if(((int)$weekoff_value === 1 || $get_common_holiday)){
							if(in_array("3",$intervening_type)){
								$leave_count = 1.00;
								$date_type   = 1;									
							}else{
								$leave_count = 0;
							}						
						}else{
							$leave_count = 1.00;
							$date_type   = 1;
						}
					}

					if((int)$weekoff_value === 1 && (int)$intervening_holidays === 1 && in_array("3",$intervening_type)){
						/* updated for TCL */
						if((int)$date_type === 1){
							$leave_count = 1.00;
						}else
						if((int)$date_type === 2 || (int)$date_type === 3){
							$leave_count = 0.50;
						}
						/* updated for TCL */
					}else
					if(((int)$weekoff_value === 2 || (int)$weekoff_value === 3) && (int)$intervening_holidays === 1 && in_array("3",$intervening_type)){
						$leave_count = 0.50;
					}else
					if((int)$intervening_holidays !== 1 && (int)$weekoff_value === 1){
						$leave_count = 0;
					}else
					if((int)$intervening_holidays !== 1 && ((int)$weekoff_value === 2 || (int)$weekoff_value === 3)){
						$leave_count = 0.50;
					}

					if($get_common_holiday && $intervening_holidays === 1 && in_array("3",$intervening_type)){
						if((int)$date_type === 1){
							$leave_count = 1.00;
						}else
						if((int)$date_type === 2 || (int)$date_type === 3){
							$leave_count = 0.50;
						}
					}else
					if((int)$intervening_holidays !== 1 && (int)$get_common_holiday){
						$leave_count = 0;
					}	
					$total_leave = $total_leave + $leave_count;

					if($leave_count > 0){
						$leave_entry_value .= '("'.$form_id.'","'.$prime_leave_financial_year_id.'","'.$component_value.'",'.'"'.$employee_code.'",'.'"'.$common_date.'",'.'"'.$leave_type.'",'.'"'.$leave_count.'",'.'"'.$date_type.'",'.'"1",'.'"'.$this->logged_id.'",'.'"'.date("Y-m-d H:i:s").'"),';
					}
				}
				if((int)$intervening_holidays === 1 && in_array("2",$intervening_type)){
					//Check after todate
					for($i=1;$i<=(int)$leave_balance;$i++){			
						$after_date = new DateTime($to_date);
						$after_date->modify("$i day");
						$check_after = $after_date->format("Y-m-d");
						//WEEKOFF DATE CHECK
						if($week_off_entry === 1){
							$after_weekoff_value = (int)$weekoff_result[$employee_code][$check_after];		
						}else
						if($week_off_entry === 2){
							$get_after_day       = strtolower(date('D',strtotime($check_after)));
							$after_day           = $days_arr[$get_after_day];
							$after_week_no       = $this->weekOfMonth(strtotime($check_after)); 
							$after_week          = $week_arr[$after_week_no];
							$after_weekoff_value = $weekoff_result[$after_day][$after_week];		
						}
						//HOLIDAY DATE CHECK
						if($holiday_entry === 2){
							$after_holiday  = $holiday_result[$check_after]['holiday_date'];
						}	
						if($after_holiday || $after_weekoff_value){
							$to_date_count = $to_date_count + 1;
							if($to_date_count){
								$leave_entry_value .= '("'.$form_id.'","'.$prime_leave_financial_year_id.'","'.$component_value.'",'.'"'.$employee_code.'",'.'"'.$check_after.'",'.'"'.$leave_type.'",'.'"1",'.'"1",'.'"1",'.'"'.$this->logged_id.'",'.'"'.date("Y-m-d H:i:s").'"),';
							}
						}else{
							break;
						}	
					}	
				}

				$total_leave = $total_leave + $from_date_count + $to_date_count;
				$leave_entry_value = rtrim($leave_entry_value,",");

				if((int)$creation_count === 0){
					echo json_encode(array('success' => FALSE, 'message' => "Leave Creation Not Available"));
					exit(0);
				}else{	
					$leave_opening_count      = "";
					if((int)$leave_opening === 1){
						$get_old_used_qry 	  = 'select count(*) as leave_opening_count,'.$pending_column.' from cw_leave_opening where employee_code = "'.$employee_code.'" and financial_setting_id = "'.$prime_leave_financial_year_id.'" and trans_status = 1';
						$get_old_used_info    = $this->db->query("CALL sp_a_run ('SELECT','$get_old_used_qry')");
						$get_old_used_result  = $get_old_used_info->result();
						$get_old_used_info->next_result();
						$leave_opening_count  = $get_old_used_result[0]->leave_opening_count;
						$pending_leave_count  = $get_old_used_result[0]->$pending_column;
					}else{
						$leave_opening_count = 1;
					}					
					if((int)$leave_opening_count === 0){
						echo json_encode(array('success' => FALSE, 'message' => "Leave Opening Not Available"));
						exit(0);
					}else{
						if($leave_entry_value){
							$request_leave_insert_qry 	 = "INSERT into cw_leave_entry (prime_request_id,financial_setting_id,component_value,employee_code,leave_date,leave_type,leave_count,date_type,leave_status,trans_created_by,trans_created_date) values $leave_entry_value";
							$request_leave_insert_info   = $this->db->query("CALL sp_a_run ('INSERT','$request_leave_insert_qry')");
							$request_leave_insert_result = $request_leave_insert_info->result();
							$request_leave_insert_info->next_result();
							$leave_entry_ins_count       = (int)$request_leave_insert_result[0]->ins_id;
							// if($request_leave_entry)
							if($leave_entry_ins_count){
								$approval_insert_key     .= "current_control,no_of_days,prime_request_id,financial_setting_id,trans_created_by,trans_created_date";
								$approval_insert_value   .= '"'.$current_control.'","'.$total_leave.'","'.$form_id.'","'.$prime_financial_id.'","'.$this->logged_id.'","'.$created_on.'"';

								$approval_insert_query = "insert into cw_approval (".$approval_insert_key.") values (".$approval_insert_value.")";
								$approval_insert_info  = $this->db->query("CALL sp_a_run ('INSERT','$approval_insert_query')");
								$approval_insert_result  = $approval_insert_info->result();
								$approval_insert_info->next_result();
							
								if((int)$leave_opening === 1) {
									$total_leave  = $pending_leave_count + $total_leave;			
									$upd_leave_opening = 'UPDATE cw_leave_opening SET '.$pending_column.' = "'.$total_leave.'",trans_updated_by = "'.$this->logged_id.'", trans_updated_date = "'.$created_on.'" WHERE cw_leave_opening.employee_code = "'.$employee_code.'" and cw_leave_opening.financial_setting_id = "'.$prime_leave_financial_year_id.'" and cw_leave_opening.trans_status = 1';
									$this->db->query("CALL sp_a_run ('UPDATE','$upd_leave_opening')");
								}

								$print_type_id = 21;
								if((int)$leave_approve_type === 1){
									return $this->send_mail($print_type_id,$form_id,$first_approval_mail,$second_approval_mail);
								}else
								if((int)$leave_approve_type === 2){
									return $this->send_mail($print_type_id,$form_id,$first_approval_mail,$second_approval_mail);
								}else
								if((int)$leave_approve_type === 3){
									return $this->send_mail($print_type_id,$form_id,$first_approval_mail,"");
								}else
								if((int)$leave_approve_type === 4){
									return $this->send_mail($print_type_id,$form_id,"",$second_approval_mail);
								}
							}
						}
					}
				}	
			}else
			if((int)$request_type === 3 || (int)$request_type === 8){
				$business_trip     = 0;
				if((int)$request_type === 8){
					$business_trip = 1;
				}
				$end_key       = end(array_keys($date_range));
				$leave_count   = 0;
				$total_leave   = 0;
				foreach ($date_range as $key => $common_date){
					//WEEKOFF DATE CHECK
					if($week_off_entry === 1){
						$weekoff_value      = (int)$weekoff_result[$employee_code][$common_date];		
					}else
					if($week_off_entry === 2){
						$get_day            = strtolower(date('D',strtotime($common_date)));
						//Check weekoff day exist
						$day                = $days_arr[$get_day];
						$week_no            = $this->weekOfMonth(strtotime($common_date)); 
						$week               = $week_arr[$week_no];
						$weekoff_value      = $weekoff_result[$day][$week];	
					}
					//HOLIDAY DATE CHECK
					if($holiday_entry === 2){
						$get_common_holiday = $holiday_result[$common_date]['holiday_date'];
					}	
					if($key === 0){
						if((int)$from_date_type === 1){
							$leave_count = 1.00;
						}else
						if((int)$from_date_type === 2 || (int)$from_date_type === 3){
							$leave_count = 0.50;
						}
						$date_type       = $from_date_type;
					}else
					if($key === $end_key){
						if((int)$to_date_type === 1){
							$leave_count = 1.00;
						}else
						if((int)$to_date_type === 2 || (int)$to_date_type === 3){
							$leave_count = 0.50;
						}
						$date_type       = $to_date_type;
					}else{
						$leave_count = 1.00;
						$date_type   = 1;
						
					}
					$total_leave = $total_leave + $leave_count;
					if($leave_count > 0){
						$on_duty_entry_value .= '("'.$form_id.'","'.$prime_leave_financial_year_id.'","'.$component_value.'","'.$employee_code.'","'.$common_date.'","'.$leave_count.'","'.$date_type.'","'.$business_trip.'","1","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
					}
				}
				$on_duty_entry_value = rtrim($on_duty_entry_value,",");
				if($on_duty_entry_value){
					$request_on_duty_insert_qry = "INSERT into cw_on_duty_entry (prime_request_id,financial_setting_id,component_value,employee_code,on_duty_date,on_duty_count,date_type,business_trip,on_duty_status,trans_created_by,trans_created_date) values $on_duty_entry_value";
					$request_on_duty_insert_info   = $this->db->query("CALL sp_a_run ('INSERT','$request_on_duty_insert_qry')");
					$request_on_duty_insert_rlst   = $request_on_duty_insert_info->result();
					$request_on_duty_insert_info->next_result();
					$on_duty_entry_ins_count       = (int)$request_on_duty_insert_rlst[0]->ins_id;

					if($on_duty_entry_ins_count){
						$approval_insert_key     .= "current_control,no_of_days,prime_request_id,financial_setting_id,trans_created_by,trans_created_date";
						$approval_insert_value   .= '"'.$current_control.'","'.$total_leave.'","'.$form_id.'","'.$prime_financial_id.'","'.$this->logged_id.'","'.$created_on.'"';

						$approval_insert_query = "insert into cw_approval (".$approval_insert_key.") values (".$approval_insert_value.")";
						$approval_insert_info  = $this->db->query("CALL sp_a_run ('INSERT','$approval_insert_query')");
						$approval_insert_result  = $approval_insert_info->result();
						$approval_insert_info->next_result();

						$print_type_id = 33;
						if((int)$leave_approve_type === 1){
							return $this->send_mail($print_type_id,$form_id,$first_approval_mail,$second_approval_mail);
						}else
						if((int)$leave_approve_type === 2){
							return $this->send_mail($print_type_id,$form_id,$first_approval_mail,$second_approval_mail);
						}else
						if((int)$leave_approve_type === 3){
							return $this->send_mail($print_type_id,$form_id,$first_approval_mail,"");
						}else
						if((int)$leave_approve_type === 4){
							return $this->send_mail($print_type_id,$form_id,"",$second_approval_mail);
						}
					}	
				}
			}		
		}		
	}
	public function cancel_entry($post_data,$form_id,$cancellation_request,$cancellation_reason){
		$created_on            = date("Y-m-d H:i:s");  
		$first_app_can_status  = 1;  
		$second_app_can_status = 1;  
		foreach ($post_data as $key => $value) {
			if($key === "employee_code"){
				$employee_code = $value;
			}
			if($key === "component_value"){
				$component_value = $value;
			}
			if($key === "request_date"){
				$key = "applied_on";
			}
			if($key === "from_date"){
				$from_date =  date('Y-m-d',strtotime($value));
			}
			if($key === "to_date"){
				$to_date =  date('Y-m-d',strtotime($value));
			}
			if($key === "in_date"){
				$in_date =  date('Y-m-d',strtotime($value));
			}
			if($key === "out_date"){
				$out_date =  date('Y-m-d',strtotime($value));
			}
			if($key === "shift_date"){
				$shift_date =  date('Y-m-d',strtotime($value));
			}
			if($key === "permission_date"){
				$permission_date =  date('Y-m-d',strtotime($value));
			}
			if($key === "first_level_approval"){
				$current_control = $value;
			}
			if($key === "request_type"){
				$request_type = $value;
			}
			if($key === "leave_approve_type"){
				$leave_approve_type = $value;
			}
			if($key === "second_level_approval"){
				$second_level_approval = $value;
			}	
			if($key === "leave_status"){
				$leave_status = $value;
			}	
			if($key === "first_approval_cancel_status"){
				$first_app_can_status = $value;
			}
			if($key === "second_approval_cancel_status"){
				$second_app_can_status = $value;
			}	
		}
		if($cancellation_request === "1"){
			//GTE DEFAULT FINANCIAL YEAR
			$financial_info     = $this->get_leave_financial_details();
			$prime_financial_id = $financial_info[0]->prime_leave_financial_year_id;
			$starting_date      = date('Y-m-d',strtotime($financial_info[0]->starting_date));	
			// $salary_end_date    = date("Y-m-d",strtotime($month_day_info["salary_end_date"]));

            //TIME OF SETTING BASED SALARY START AND END DATE DETAILS
            $month_day_info     = $this->tos_day_info($employee_code,"3"); // 3 => Leave Entry
			if(count($month_day_info)){
				$salary_start_date  = date("Y-m-d",strtotime($month_day_info["salary_start_date"]));
				// $salary_end_date    = date("Y-m-d",strtotime($month_day_info["salary_end_date"]));
				$salary_end_date    = date("Y-m-d",strtotime($month_day_info["year_end_date"]));

				$check_sts          = false;
				if($request_type === "1" || $request_type === "2" || $request_type === "3" || $request_type === "8"){ 
					if($from_date >= $salary_start_date && $to_date <= $salary_end_date){
						$check_sts  = true;
					}
				}else
				if($request_type === "4" || $request_type === "5"){
					if($permission_date >= $salary_start_date){
						$check_sts  = true;
					}
				}else
				if($request_type === "6"){
					if($shift_date >= $salary_start_date){
						$check_sts  = true;
					}
				}else
				if($request_type === "7"){
					if($shift_date >= $salary_start_date){
						$check_sts  = true;
					}
				}
				if($check_sts){
					$upd_approval_qry           = 'UPDATE cw_approval SET first_level_approval = "'. $current_control .'",second_level_approval = "'. $second_level_approval .'",cancellation_request = "'. $cancellation_request .'",cancellation_reason = "'. $cancellation_reason .'",leave_status = "'. $leave_status .'",first_approval_cancel_status = "'.$first_app_can_status.'",second_approval_cancel_status = "'. $second_app_can_status.'",trans_updated_by = "'.$this->logged_id.'", trans_updated_date = "'.$created_on.'" WHERE prime_request_id = "'.$form_id.'" and cw_approval.trans_status = 1';
					$this->db->query("CALL sp_a_run ('UPDATE','$upd_approval_qry')");

					$employee_detail_qry  		= 'select prime_employees_id,first_level_approval,second_level_approval from cw_employees where employee_code = "'.$employee_code.'" and trans_status = 1';
					$employee_detail_info  		= $this->db->query("CALL sp_a_run ('SELECT','$employee_detail_qry')");
					$employee_detail_result  	= $employee_detail_info->result();
					$employee_detail_info->next_result();
					$view_id 					= $employee_detail_result[0]->prime_employees_id;
					$first_level_approval_code	= $employee_detail_result[0]->first_level_approval;
					$second_level_approval_code	= $employee_detail_result[0]->second_level_approval;
					$first_approval_qry  	    = 'select company_email_id from cw_employees where employee_code = "'.$first_level_approval_code.'" and trans_status = 1';
					$first_approval_info  	    = $this->db->query("CALL sp_a_run ('SELECT','$first_approval_qry')");
					$first_approval_result      = $first_approval_info->result();
					$first_approval_info->next_result();
					$first_approval_mail 	    = $first_approval_result[0]->company_email_id;

					$second_approval_qry  	    = 'select company_email_id from cw_employees where employee_code = "'.$second_level_approval_code.'" and trans_status = 1';
					$second_approval_info  	    = $this->db->query("CALL sp_a_run ('SELECT','$second_approval_qry')");
					$second_approval_result     = $second_approval_info->result();
					$second_approval_info->next_result();
					$second_approval_mail 	    = $second_approval_result[0]->company_email_id;
					$print_type_id              = "";
					if($request_type === "1" || $request_type === "2"){ 
						$print_type_id = 24;
					}else
					if($request_type === "3" || $request_type === "8"){ 
						$print_type_id = 36;
					}else
					if($request_type === "4" || $request_type === "5"){
						$print_type_id = 30;
					}else
					if($request_type === "6"){
						$print_type_id = 42;
					}else
					if($request_type === "7"){
						$print_type_id = 48;
					}
					if((int)$leave_approve_type === 1){
						return $this->send_mail($print_type_id,$form_id,$first_approval_mail,$second_approval_mail);
					}else
					if((int)$leave_approve_type === 2){
						return $this->send_mail($print_type_id,$form_id,$first_approval_mail,$second_approval_mail);
					}else
					if((int)$leave_approve_type === 3){
						return $this->send_mail($print_type_id,$form_id,$first_approval_mail,"");
					}else
					if((int)$leave_approve_type === 4){
						return $this->send_mail($print_type_id,$form_id,"",$second_approval_mail);
					}
					return true;
				}else{
					echo json_encode(array('success' => FALSE, "message" => "Could not Cancel.. Because Payroll Already Processed for this Month...!"));
					exit(0);
				}
			}else{
				echo json_encode(array('success' => FALSE, 'message' => "Please Set Month Day for this Category..."));
				exit(0);
			}
		}
	}
	public function weekOfMonth($date) {
	    //Get the first day of the month.
	    $firstOfMonth = strtotime(date("Y-m-01", $date));
	    //Apply above formula.
	    return $this->weekOfYear($date) - $this->weekOfYear($firstOfMonth) + 1;
	}
	public function weekOfYear($date) {
	    $weekOfYear = intval(date("W", $date));
	    if (date('n', $date) == "1" && $weekOfYear > 51) {
	        // It's the last week of the previos year.
	        $weekOfYear = 0;    
	    }
	    return $weekOfYear;
	}

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

	//UPDATE STATUS TO DELETE FOR UPLOAD FILES or DOCUMENTS
	public function remove_file(){
		//Encryption
		$encString     = file_get_contents('php://input');
		$_POST         = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Url Expired.. Please refresh the page and try again....','table_data' => ""));
			exit(0);
		}
		$prime_id_val  = $this->input->post('prime_id_val');
		$is_defult     = (int)$this->input->post('is_defult');
		$input_name     = $this->input->post('input_name');
		$table_name = '';
		if($is_defult === 1){
			$table_name = $this->prime_table;
		}else
		if($is_defult === 2){
			$table_name = $this->cf_table;
		}
		if($table_name){
			$created_on    = date("Y-m-d h:i:s");
			$set_query     = $input_name .' = "" ,trans_updated_by = "'. $this->logged_id .'",trans_updated_date = "'.$created_on.'"';
			$update_query  = 'UPDATE '.$table_name .' SET '. $set_query .' WHERE '. $this->prime_id .' = "'. $prime_id_val .'"';
			$this->db->query("CALL sp_a_run ('UPDATE','$update_query')");
			echo json_encode(array('success' => TRUE, 'message' => "Successfully updated"));
		}else{
			echo json_encode(array('success' => FALSE, 'message' => "Unable to process your request"));
		}
	}
	
	//IMPORT FILE VIEW INFORMATION
	public function import(){
		$data['module_id']     = $this->control_name;		
		$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);
	}
	function getDatesFromRange($start, $end, $format = 'Y-m-d') {
      
	    // Declare an empty array
	    $array = array();
	      
	    // Variable that store the date interval
	    // of period 1 day
	    $interval = new DateInterval('P1D');
	  
	    $realEnd = new DateTime($end);
	    $realEnd->add($interval);
	  
	    $period = new DatePeriod(new DateTime($start), $interval, $realEnd);
	  
	    // Use loop to store date into array
	    foreach($period as $date) {                 
	        $array[] = $date->format($format); 
	    }
	  
	    // Return the array elements
	    return $array;
	}
	public function send_mail($print_type_id,$view_id,$first_approval_mail,$second_approval_mail){
		$email_data     	  = $this->load_email_data($print_type_id,$view_id);
		$body_content   	  = "<!DOCTYPE html><html> <body>".$email_data['print_design']."</body></html>";
		$email_design_query   = 'select prime_print_info_id,email_design,print_info_for,print_info_module_id,print_type,email_subject,email_bcc,to_email 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("'.$this->logged_role.'",print_info_for) and print_info_module_id = "'.$this->control_name.'" and cw_print_info.trans_status = 1 and print_type = "'.$print_type_id.'"';
		$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 			  = $email_design_result[0]->email_bcc;
		$to_email 			  = $email_design_result[0]->to_email;
		return $this->send_email_notification($to_email,$first_approval_mail,$second_approval_mail,$email_bcc,$mail_subject,$body_content,'');
	}

	public function leave_balance_count(){
		$encString           = file_get_contents('php://input');
		$_POST               = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Url Expired.. Please refresh the page and try again....','table_data' => ""));
			exit(0);
		}
		$leave_type          = $this->input->post('leave_type');
		if($this->config->item("db_name") === 'tcl_hrms' || $this->config->item("db_name") === 'tcl_dev'){
			$employee_code   = $this->input->post('employee_code');
		}else{
			$employee_code   = $this->session->userdata('logged_emp_code');
		}
		
		$financial_info      = $this->get_leave_financial_details();
		$prime_financial_id  = $financial_info[0]->prime_leave_financial_year_id;

		$leave_name_query  = 'SELECT lower(leave_name) as leave_name,leave_opening from cw_leave_creation WHERE prime_leave_creation_id = "'. $leave_type .'" and trans_status = 1 ';
		$leave_name_info   = $this->db->query("CALL sp_a_run ('SELECT','$leave_name_query')");
		$leave_name_rlst   = $leave_name_info->result();
		$leave_name_info->next_result();
		$leave_name        = $leave_name_rlst[0]->leave_name;
		$leave_opening     = $leave_name_rlst[0]->leave_opening;
		$leave_balance = 0;
	if((int)$leave_opening === 1){
		$leave_balance_query  = 'SELECT (('.$leave_name.'+'.$leave_name.'_credit)-('.$leave_name.'_debit + used_'.$leave_name.'+ pending_'.$leave_name.'+ encash_'.$leave_name.')) as leave_balance from cw_leave_opening where employee_code = "'.$employee_code.'" and cw_leave_opening.trans_status = 1 and financial_setting_id = "'.$prime_financial_id.'"';
		$leave_balance_info   = $this->db->query("CALL sp_a_run ('SELECT','$leave_balance_query')");
		$leave_balance_rlst   = $leave_balance_info->result();
		$leave_balance_info->next_result();
		$leave_balance        = $leave_balance_rlst[0]->leave_balance;
	}

		echo json_encode(array('success' => TRUE, 'leave_balance' => $leave_balance, 'leave_opening' => $leave_opening));
	}

	public function check_is_holiday(){
		$encString           = file_get_contents('php://input');
		$_POST               = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Url Expired.. Please refresh the page and try again....','table_data' => ""));
			exit(0);
		}
		$from                = $this->input->post('from');	
		$from_date           = date("Y-m-d",strtotime($this->input->post('from_date')));
		$to_date             = date("Y-m-d",strtotime($this->input->post('to_date')));
		$from_date_type      = (int)$this->input->post('from_date_type');		
		$to_date_type        = (int)$this->input->post('to_date_type');		
		//$component_value     = $this->input->post('component_value');		
		if($this->config->item("db_name") === 'tcl_hrms' || $this->config->item("db_name") === 'tcl_dev'){
			$employee_code   = $this->input->post('employee_code');
		}else{
			$employee_code   = $this->session->userdata('logged_emp_code');
		}	
		$financial_info      = $this->get_leave_financial_details();
		$prime_financial_id  = $financial_info[0]->prime_leave_financial_year_id;	
		$get_year            = "";
		$get_day             = "";
		$check_date          = "";
		if($from === "from_date_type"){
			$get_year        = date("Y", strtotime($from_date));
			$get_day         = strtolower(date('D',strtotime($from_date)));
			$check_date      = $from_date;
		}else
		if($from === "to_date_type"){
			$get_year        = date("Y", strtotime($to_date));
			$get_day         = strtolower(date('D',strtotime($to_date)));
			$check_date      = $to_date;
		}
		
		//SELECT QUERY FOR CHECK A GENENRAL SETTING PARAMETER BASED TYPE
		$param_based_type_qry  = 'SELECT parameter_type,based_on FROM cw_general_setting inner join cw_parameter_type on cw_parameter_type.prime_parameter_type_id = cw_general_setting.entry_parameter_type WHERE cw_general_setting.trans_status = 1';
		$param_based_type_info = $this->db->query("CALL sp_a_run ('SELECT','$param_based_type_qry')");
		$param_based_type_rslt = $param_based_type_info->result_array();
		$param_based_type_info->next_result();

		$param_based_type_arr  = array_reduce($param_based_type_rslt, function($result, $arr){			
	    	$result[$arr['parameter_type']] = $arr['based_on'];
	    	return $result;
		}, array());

		$week_off_entry        = (int)$param_based_type_arr['Weekly off Entry'];	
		$holiday_entry         = (int)$param_based_type_arr['Holiday Entry'];	
		$leave_entry           = (int)$param_based_type_arr['Leave Entry'];	
		$sts                   = false;
		//check in general setting module for weekoff and holiday check or not for all request
		$general_setting_info  = $this->general_setting_info();
		$weekoff_check         = (int)$general_setting_info[0]->check_parameter;
		if($weekoff_check === 2){
			$sts  = true;
		}else{
			//CONDITION FOR CHECK A WEEKOFF DATE FOR PARAMETER TYPE BASED ON
			if($week_off_entry === 1){
				$check_weekoff_qry   = 'SELECT employee_code,weekoff_date,weekoff_type from cw_weekoff_import WHERE employee_code = "'. $employee_code .'" and weekoff_date = "'.$check_date.'" and financial_setting_id = '.$prime_financial_id.' and trans_status = 1';
				$check_weekoff_info   = $this->db->query("CALL sp_a_run ('SELECT','$check_weekoff_qry')");
				$check_weekoff_rlst   = $check_weekoff_info->result_array();
				$check_weekoff_info->next_result();

				$check_weekoff_arr  = array_reduce($check_weekoff_rlst, function($result, $arr){			
				    $result[$arr['employee_code']][$arr['weekoff_date']] = $arr['weekoff_type'];
				    return $result;
				}, array());

				if(!empty($check_weekoff_arr)){
					if($from === "from_date_type"){
						$check_weekoff_date_type  = (int)$check_weekoff_arr[$employee_code][$from_date];
						if($check_weekoff_date_type === 1 || $from_date_type === $check_weekoff_date_type){
							echo json_encode(array('success' => true,'from'=>"weekoff",'message' => "You have Choosed Weekoff day.. Please Choose Another Date", 'weekoff_type' => $weekoff_date));
							exit(0);
						}else
						if($check_weekoff_date_type !==1){
							if($from_date_type === 1){
								echo json_encode(array('success' => true,'from'=>"weekoff",'message' => "You have Choosed Weekoff day.. Please Choose Another Date", 'weekoff_type' => $weekoff_date));
								exit(0);
							}else{
								$sts  = true;
							}
						}else{
							$sts  = true;
						}

					}else
					if($from === "to_date_type"){
						$check_weekoff_date_type  = (int)$check_weekoff_arr[$employee_code][$to_date];
						if($check_weekoff_date_type === 1 || $to_date_type === $check_weekoff_date_type){
							echo json_encode(array('success' => true,'from'=>"weekoff",'message' => "You have Choosed Weekoff day.. Please Choose Another Date", 'weekoff_type' => $weekoff_date));
							exit(0);
						}else
						if($check_weekoff_date_type !==1){
							if($to_date_type === 1){
								echo json_encode(array('success' => true,'from'=>"weekoff",'message' => "You have Choosed Weekoff day.. Please Choose Another Date", 'weekoff_type' => $weekoff_date));
								exit(0);
							}else{
								$sts  = true;
							}
						}else{
							$sts  = true;
						}
					}
				}else{
					$sts  = true;
				}
			}else{
				//QUERY AND CODE ARE USED FOR GET A WEEK OFF AND HOLIDAY DETAILS
				$week_component_query  = 'SELECT label_name,components FROM cw_general_setting inner join cw_form_setting on cw_form_setting.prime_form_id = cw_general_setting.components WHERE entry_parameter_type = 1 and cw_general_setting.trans_status = 1';
				$week_component_info   = $this->db->query("CALL sp_a_run ('SELECT','$week_component_query')");
				$week_component_result = $week_component_info->result();
				$week_component_info->next_result();
				
				$week_label_name       = $week_component_result[0]->label_name;
				//$week_comp_value       = $this->emp_pick_arr[$employee_code][$week_label_name];
				$emp_pick_arr          = $this->get_emp_data();
				$week_comp_value       = $emp_pick_arr[$employee_code][$week_label_name];
				$weekoff_qry = 'select cw_weekoff_entry_weekoff_days_details.weekday,cw_weekoff_entry_weekoff_days_details.first_week,cw_weekoff_entry_weekoff_days_details.second_week,cw_weekoff_entry_weekoff_days_details.third_week,cw_weekoff_entry_weekoff_days_details.fourth_week,cw_weekoff_entry_weekoff_days_details.fifth_week from cw_weekoff_entry inner join cw_weekoff_entry_weekoff_days_details on cw_weekoff_entry_weekoff_days_details.prime_weekoff_entry_id = cw_weekoff_entry.prime_weekoff_entry_id where FIND_IN_SET("'.$week_comp_value.'", cw_weekoff_entry.component_value) and (cw_weekoff_entry.from_date <= "'.$from_date.'" AND cw_weekoff_entry.to_date >= "'.$from_date.'" or cw_weekoff_entry.from_date <= "'.$to_date.'" AND cw_weekoff_entry.to_date >= "'.$to_date.'") and cw_weekoff_entry.trans_status = 1 and cw_weekoff_entry_weekoff_days_details.trans_status = 1';

				$weekoff_info      = $this->db->query("CALL sp_a_run ('SELECT','$weekoff_qry')");
				$weekoff_result    = $weekoff_info->result_array();
				$weekoff_info->next_result();

				if($weekoff_result){
					$weekoff_result    = array_reduce($weekoff_result, function($result, $arr){			
				    $result[$arr['weekday']] = $arr;
				    return $result;
					}, array());
					/* Weekoff - END */
					$days_arr = array("sun"=>1,"mon"=>2,"tue"=>3,"wed"=>4,"thu"=>5,"fri"=>6,"sat"=>7);
					$week_arr = array(1=>"first_week",2=>"second_week",3=>"third_week",4=>"fourth_week",5=>"fifth_week");				
					//Check weekoff day exist
					$day                = $days_arr[$get_day];
					$week_no            = $this->weekOfMonth(strtotime($check_date)); 
					$week               = $week_arr[$week_no];
					$weekoff_date       = $weekoff_result[$day][$week];
					if($weekoff_date){
						echo json_encode(array('success' => true,'from'=>"weekoff",'message' => "You have Choosed Weekoff day.. Please Choose Another Date", 'weekoff_type' => $weekoff_date));
						exit(0);
					}else{
						$sts   = true;
					}
				}else{
					$sts   = true;
				}				
			}
		}
		//check in general setting module for weekoff and holiday check or not for all request
		$general_setting_info  = $this->general_setting_info();
		$holiday_check         = (int)$general_setting_info[1]->check_parameter;
		if($holiday_check === 2){
			echo json_encode(array('success' => false));
		}else{
			//CONDITION FOR CHECK A HOLIDAY DATE FOR PARAMETER TYPE BASED ONCE
			if($holiday_entry === 2){
				if($sts){
					$holid_component_query  = 'SELECT label_name,components FROM cw_general_setting inner join cw_form_setting on cw_form_setting.prime_form_id = cw_general_setting.components WHERE entry_parameter_type = 2 and cw_general_setting.trans_status = 1';
					$holid_component_info   = $this->db->query("CALL sp_a_run ('SELECT','$holid_component_query')");
					$holid_component_result = $holid_component_info->result();
					$holid_component_info->next_result();	
				
					$holid_label_name    = $holid_component_result[0]->label_name;
					//$holid_comp_value    = $this->emp_pick_arr[$employee_code][$holid_label_name];
					$emp_pick_arr        = $this->get_emp_data();
					$holid_comp_value    = $emp_pick_arr[$employee_code][$holid_label_name];

					$holiday_qry         = 'select count(*) as count from cw_holiday_entry inner join cw_holiday_entry_holiday_data on cw_holiday_entry_holiday_data.prime_holiday_entry_id = cw_holiday_entry.prime_holiday_entry_id where FIND_IN_SET("'.$holid_comp_value.'", cw_holiday_entry_holiday_data.component_value) and cw_holiday_entry.holiday_year = "'.$get_year.'" and (cw_holiday_entry_holiday_data.holiday_date = "'.$from_date.'" or cw_holiday_entry_holiday_data.holiday_date = "'.$to_date.'") and cw_holiday_entry.trans_status = 1 and cw_holiday_entry_holiday_data.trans_status = 1';
					$holiday_info       = $this->db->query("CALL sp_a_run ('SELECT','$holiday_qry')");
					$holiday_result     = $holiday_info->result();
					$holiday_info->next_result();

					$holiday_count   = $holiday_result[0]->count;
					if($holiday_count){
						echo json_encode(array('success' => true,'from'=>"holiday",'message' => "You have Choosed Holiday.. Please choose Another Date", 'holiday_count' => $holiday_count));
					}else{
						echo json_encode(array('success' => false));
					}
				}
				// else{
				// 	echo json_encode(array('success' => false));
				// }
			}
		}
	}
	//check leave validation
	public function view_leave_status(){
		$encString           = file_get_contents('php://input');
		$_POST               = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Url Expired.. Please refresh the page and try again....','table_data' => ""));
			exit(0);
		}
		$component_value     = $this->input->post('component_value');
		if($this->config->item("db_name") === 'tcl_hrms' || $this->config->item("db_name") === 'tcl_dev'){
			$employee_code   = $this->input->post('employee_code');
		}else{
			$employee_code   = $this->session->userdata('logged_emp_code');
		}
		$request_type        = $this->input->post('request_type');
		$leave_type          = $this->input->post('leave_type');
		$from_date           = $this->input->post('from_date');
		$to_date             = $this->input->post('to_date');
		$from_date_type      = $this->input->post('from_date_type');
		$to_date_type        = $this->input->post('to_date_type');
		$leave_balance       = $this->input->post('leave_balance');
		$same_date = 0;
		if($from_date === $to_date){
			$same_date = 1;
		}
		$financial_info      = $this->get_leave_financial_details();
		$prime_financial_id  = $financial_info[0]->prime_leave_financial_year_id;
		//
		$get_emp_query    = 'SELECT role from cw_employees WHERE employee_code = "'. $employee_code .'" and trans_status = 1';
		$get_emp_info     = $this->db->query("CALL sp_a_run ('SELECT','$get_emp_query')");
		$get_emp_rlst     = $get_emp_info->result();
		$get_emp_info->next_result();
		$emp_category     = $get_emp_rlst[0]->role;
		$from_month       = date("m-Y",strtotime($from_date));
		$to_month         = date("m-Y",strtotime($to_date));
		$leave_export_query    = 'SELECT process_month from cw_leave_export WHERE category = "'. $emp_category .'" and trans_status = 1';
		$leave_export_info     = $this->db->query("CALL sp_a_run ('SELECT','$leave_export_query')");
		$leave_export_rlst     = $leave_export_info->result_array();
		$leave_export_info->next_result();

		$leave_export_arr    = array_reduce($leave_export_rlst, function($result, $arr){			
	    	$result[$arr['process_month']] = $arr;
	    	return $result;
		}, array());

		//SAME LEAVE TYPE ALREADY EXIST 
		if((int)$request_type === 1){ //LEAVE REQUEST
			$from_leave_exist_qry  = 'SELECT count(*) as from_exist_count  from cw_leave_entry WHERE employee_code = "'. $employee_code .'" and leave_date = date_format(str_to_date("'.$from_date.'", "%d-%m-%Y") , "%Y-%m-%d") and financial_setting_id = '.$prime_financial_id.' and leave_status not in (3,4) and leave_type = '.$leave_type.' and trans_status = 1';
			$frm_leave_exist_info  = $this->db->query("CALL sp_a_run ('SELECT','$from_leave_exist_qry')");
			$frm_leave_exist_rslt  = $frm_leave_exist_info->result();
			$frm_leave_exist_info->next_result();		

			$to_leave_exist_qry  = 'SELECT count(*) as to_exist_count  from cw_leave_entry WHERE employee_code = "'. $employee_code .'" and leave_date = date_format(str_to_date("'.$to_date.'", "%d-%m-%Y") , "%Y-%m-%d") and financial_setting_id = '.$prime_financial_id.' and leave_status not in (3,4) and leave_type = '.$leave_type.' and trans_status = 1';
			$to_leave_exist_info      = $this->db->query("CALL sp_a_run ('SELECT','$to_leave_exist_qry')");
			$to_leave_exist_rslt      = $to_leave_exist_info->result();
			$to_leave_exist_info->next_result();
			$from_exist_rslt  = (int)$frm_leave_exist_rslt[0]->from_exist_count;
			$to_exist_rslt    = (int)$to_leave_exist_rslt[0]->to_exist_count;
			if($from_exist_rslt  > 0 || $to_exist_rslt > 0){
				echo json_encode(array('success' => TRUE, 'message' => "Same Leave type Already Exist for this given Date...!"));
				exit();
			}
		}

		if((int)$request_type === 3){  //ON DUTY 
			$frm_date          = date('Y-m-d',strtotime($from_date));
			$end_date          = date('Y-m-d',strtotime($to_date));
			$on_duty_chk_qry   = 'SELECT COUNT(*) AS count FROM cw_on_duty_entry WHERE employee_code = "'.$employee_code.'" and date_format(str_to_date(on_duty_date, "%Y-%m-%d"),"%Y-%m-%d") between ("'.$frm_date.'") and ("'.$end_date.'") AND on_duty_status IN(1,2) AND trans_status=1';
			$on_duty_info      = $this->db->query("CALL sp_a_run ('SELECT','$on_duty_chk_qry')");
			$on_duty_rslt      = $on_duty_info->result();
			$on_duty_info->next_result();
			if((int)$on_duty_rslt[0]->count > 0){
				echo json_encode(array('success' => TRUE, 'message' => "Already On Duty Applied For This Date..."));
				exit();
			}
		}

		if($leave_export_arr){
			$month_day_result      = $this->tos_day_qry_fun("Leave Entry");
	        $check_leave_month     = "";
			if($month_day_result){
				$day_conditions    = $month_day_result[0]->day_conditions;
				$day_count         = $month_day_result[0]->day_count;
				$day_start         = $month_day_result[0]->day_start;
				$day_end           = $month_day_result[0]->day_end;
				$cur_month         = date('m-Y');
				$leave_from_date   = date("Y-m-d",strtotime($from_date));
				$leave_to_date     = date("Y-m-d",strtotime($to_date));
				$check_leave_arr= array();
				if((int)$day_conditions === 3){
					$sal_start = $day_start;
					//For Current month between days increment
					$date = new DateTime("01-$cur_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."-".$cur_month));

					if(($leave_from_date >= $salary_start_date) && ($leave_from_date <= $salary_end_date)
						&& ($leave_to_date >= $salary_start_date) && ($leave_to_date <= $salary_end_date)){
						$check_leave_month   = date('m-Y',strtotime($salary_end_date));
					}else
					if($salary_start_date <= $leave_from_date && $salary_end_date >= $leave_from_date && $salary_end_date < $leave_to_date){
						$check_leave_month   = date('m-Y',strtotime($salary_end_date));
					}else
					if($salary_start_date > $leave_from_date){
						$check_leave_month   = date('m-Y',strtotime($salary_start_date));
					}else
					if($salary_end_date < $leave_from_date){
						$check_leave_month   = date('m-Y',strtotime("+1 month",strtotime($salary_end_date)));
					}
				}else{
					$sal_start = '01';
					$date = new DateTime("01-$cur_month 00:00:00");
					$salary_start_date = $date->format("Y-m-$sal_start");	
					$salary_end_date   = date("Y-m-d",strtotime($day_end."-".$cur_month));

					if($salary_start_date <= $leave_from_date && $salary_end_date >= $leave_from_date && $salary_start_date <= $leave_to_date && $salary_end_date >= $leave_to_date){
						$check_leave_month  = date('m-Y',strtotime($salary_start_date));
					}else
					if($salary_start_date <= $from_date && $salary_end_date >= $from_date && $salary_end_date < $leave_to_date){
						$check_leave_month  = date('m-Y',strtotime($salary_end_date));
					}else
					if($salary_start_date > $leave_from_date){
						$check_leave_month  =  date('m-Y',strtotime("-1 month",strtotime($salary_end_date)));
					}else
					if($salary_end_date < $leave_from_date){
						$check_leave_month  =  date('m-Y',strtotime("+1 month",strtotime($salary_end_date)));
					}
				}
				if($check_leave_month){
					if(array_key_exists($check_leave_month,$leave_export_arr)){
						echo json_encode(array('success' => TRUE, 'message' => "Don't Leave Applied"));
						exit();
					}
				}
			}
		}
		$check_leave_query   = 'SELECT leave_date,leave_count,leave_type from cw_leave_entry WHERE employee_code = "'. $employee_code .'" and leave_date between (date_format(str_to_date("'.$from_date.'", "%d-%m-%Y") , "%Y-%m-%d")) and (date_format(str_to_date("'.$to_date.'", "%d-%m-%Y") , "%Y-%m-%d")) and financial_setting_id = '.$prime_financial_id.' and leave_status not in (3,4) and trans_status = 1';
		$check_leave_info   = $this->db->query("CALL sp_a_run ('SELECT','$check_leave_query')");
		$check_leave_rlst   = $check_leave_info->result_array();
		$check_leave_info->next_result();
		//FROM ON DUTY ENTRY TABLE FOR ON DUTY 
		$check_on_duty_query   = 'SELECT on_duty_date,on_duty_count from cw_on_duty_entry WHERE employee_code = "'. $employee_code .'" and on_duty_date between (date_format(str_to_date("'.$from_date.'", "%d-%m-%Y") , "%Y-%m-%d")) and (date_format(str_to_date("'.$to_date.'", "%d-%m-%Y") , "%Y-%m-%d")) and financial_setting_id = '.$prime_financial_id.' and on_duty_status not in (3,4) and trans_status = 1';
		$check_on_duty_info   = $this->db->query("CALL sp_a_run ('SELECT','$check_on_duty_query')");
		$check_on_duty_rlst   = $check_on_duty_info->result_array();
		$check_on_duty_info->next_result();
		$check_leave_rlst    = array_reduce($check_leave_rlst, function($result, $arr){			
	    	$result[date("d-m-Y",strtotime($arr['leave_date']))] = $arr;
	    	return $result;
		}, array());

		$check_on_duty_rlst    = array_reduce($check_on_duty_rlst, function($result, $arr){			
	    	$result[date("d-m-Y",strtotime($arr['on_duty_date']))] = $arr;
	    	return $result;
		}, array());

		$check_request_rlst   = "";
		$direct_leave_rlst    = "";
		$check_request_query  = 'SELECT from_date,to_date,from_date_type,to_date_type,request_type from cw_request WHERE employee_code = "'. $employee_code .'" and financial_setting_id = '.$prime_financial_id.' and leave_status not in (3,4) and trans_status = 1';
		$check_request_info   = $this->db->query("CALL sp_a_run ('SELECT','$check_request_query')");
		$check_request_rlst   = $check_request_info->result_array();
		$check_request_info->next_result();
		//CHECK A DIRECT LEAVE ENTRY TABLE FOR THIS SAME DATE ALREADY LEAVE APPLIED OR NOT
		$direct_leave_query  = 'SELECT from_date,to_date,from_date_type,to_date_type,request_type from cw_direct_leave_entry WHERE employee_code = "'. $employee_code .'" and financial_setting_id = '.$prime_financial_id.' and trans_status = 1';
		$direct_leave_info   = $this->db->query("CALL sp_a_run ('SELECT','$direct_leave_query')");
		$direct_leave_rlst   = $direct_leave_info->result_array();
		$direct_leave_info->next_result();

		$request_from_rlst   = array_reduce($check_request_rlst, function($result, $arr){			
	    	$result[date("d-m-Y",strtotime($arr['from_date']))][] = $arr['from_date_type'];
	    	return $result;
		}, array());

		$request_from_type   = array_reduce($check_request_rlst, function($result, $arr){			
	    	$result[date("d-m-Y",strtotime($arr['from_date']))] = $arr['request_type'];
	    	return $result;
		}, array());

		$request_to_rlst     = array_reduce($check_request_rlst, function($result, $arr){			
	    	$result[date("d-m-Y",strtotime($arr['to_date']))][] = $arr['to_date_type'];
	    	return $result;
		}, array());

		$request_to_type     = array_reduce($check_request_rlst, function($result, $arr){			
	    	$result[date("d-m-Y",strtotime($arr['to_date']))] = $arr['request_type'];
	    	return $result;
		}, array());		

		$direct_leave_from_rlst  = array_reduce($direct_leave_rlst, function($result, $arr){	
			$result[date("d-m-Y",strtotime($arr['from_date']))][] = $arr['from_date_type'];
			return $result;
		}, array());

		$direct_leave_from_type  = array_reduce($direct_leave_rlst, function($result, $arr){		
			$result[date("d-m-Y",strtotime($arr['from_date']))] = $arr['request_type'];
			return $result;
		}, array());

		$direct_leave_to_rlst    = array_reduce($direct_leave_rlst, function($result, $arr){	
			$result[date("d-m-Y",strtotime($arr['to_date']))][] = $arr['to_date_type'];
			return $result;
		}, array());

		$direct_leave_to_type    = array_reduce($direct_leave_rlst, function($result, $arr){	
			$result[date("d-m-Y",strtotime($arr['to_date']))] = $arr['request_type'];
			return $result;
		}, array());

		$request_from_rlst   = array_merge($request_from_rlst, $direct_leave_from_rlst);
		$request_from_type   = array_merge($request_from_type, $direct_leave_from_type);
		$request_to_rlst     = array_merge($request_to_rlst , $direct_leave_to_rlst);
		$request_to_type     = array_merge($request_to_type , $direct_leave_to_type);


		//SK AND DK LEAVE ALLOW VALIDATION
		$from_date_arr       = array();
		$to_date_arr         = array();
		$check_request_type  = "";

		if(array_key_exists($from_date,$request_from_rlst) || array_key_exists($to_date,$request_from_rlst)){
			if($request_from_rlst[$from_date]){
				$from_date_arr[$from_date] = $request_from_rlst[$from_date][0];
			}
			if($request_from_rlst[$to_date]){				
				$from_date_arr[$to_date]   = $request_from_rlst[$to_date][0];				
			}			
		}
		if(array_key_exists($from_date,$request_to_rlst) || array_key_exists($to_date,$request_to_rlst)){
			if($request_to_rlst[$from_date]){
				if($request_to_rlst[$from_date][0] && $request_to_rlst[$from_date][1]){
					$to_date_arr[$from_date]   = $request_to_rlst[$from_date][1];
				}else{
					$to_date_arr[$from_date]   = $request_to_rlst[$from_date][0];
				}
				
			}
			if($request_to_rlst[$to_date]){
				if($request_to_rlst[$to_date][0] && $request_to_rlst[$to_date][1]){
					$to_date_arr[$to_date]     = $request_to_rlst[$to_date][1];
				}else{
					$to_date_arr[$to_date]     = $request_to_rlst[$to_date][0];
				}				
			}
		}
		$check_exist         = 0;
		$from_leave_allow    = 0;
		$to_leave_allow      = 0;
		$message             = "";	
		if(array_key_exists($from_date,$from_date_arr)){
			if($from_date_arr[$from_date] === $from_date_type || $to_date_arr[$from_date] === $from_date_type || (int)$from_date_type === 1){
				$check_exist         = 1;	
				$check_request_type  = $request_from_type[$from_date];
				if($to_date_arr[$from_date] === $from_date_type){
					$check_request_type  = $request_to_type[$from_date];
				}		
			}else{
				if((int)$from_date_arr[$from_date] === 1){
					$check_exist = 1;
					$check_request_type  = $request_from_type[$from_date];	
				}else
				if((int)$from_date_arr[$from_date] === 2){
					$from_leave_allow = 3;
					$check_exist = 1;
				}else{
					$from_leave_allow = 2;
					$check_exist = 1;
				}						
			}	
			// $message = "You are Already Leave Applied in this From Date..";
		}else
		/* SATHISH - START */
		if(array_key_exists($from_date,$to_date_arr)){
			if($from_date_arr[$from_date] === $from_date_type || (int)$from_date_arr[$from_date] === 1 || (int)$from_date_type === 1){
				$check_exist = 1;		
				$check_request_type  = $request_from_type[$from_date];			
			}else{
				if((int)$to_date_arr[$from_date] === 1){
					$check_exist = 1;
					$check_request_type  = $request_to_type[$from_date];			
				}else
				if((int)$to_date_arr[$from_date] === 2){
					$from_leave_allow = 3;
					$check_exist = 1;
				}else{
					$from_leave_allow = 2;
					$check_exist = 1;
				}						
			}	
		}
		/* SATHISH - END */
		if(array_key_exists($to_date,$to_date_arr)){
			if($from_date_arr[$to_date] === $to_date_type || $to_date_arr[$to_date] === $to_date_type || (int)$to_date_type === 1){
				$check_exist = 2;
				if($from_date_arr[$to_date] === $to_date_type){
					$check_request_type  = $request_from_type[$to_date];
				}
				$check_request_type  = $request_to_type[$to_date];			
			}else{
				if((int)$to_date_arr[$to_date] === 1){
					$check_exist = 2;
					
					$check_request_type  = $request_to_type[$to_date];	
				}else
				if((int)$to_date_arr[$to_date] === 2){
					$to_leave_allow = 3;
					$check_exist = 2;
					
				}else{
					$to_leave_allow = 2;
					$check_exist = 2;
				}		
			}	
			// $message = "You are Already Leave Applied in this To Date..";
		}else
		if(array_key_exists($to_date,$from_date_arr)){
			/* SATHISH - START */
			if($from_date_arr[$to_date] === $to_date_type || (int)$from_date_arr[$to_date] === 1 || (int)$to_date_type === 1){
				$check_exist = 2;
				$check_request_type  = $request_from_type[$to_date];	
			}else{
				if((int)$to_date_arr[$to_date] === 1){
					$check_exist = 2;
					$check_request_type  = $request_to_type[$to_date];	
				}else
				if((int)$to_date_arr[$to_date] === 2){
					$to_leave_allow = 3;
					$check_exist = 2;
				}else{
					$to_leave_allow = 2;
					$check_exist = 2;
				}		
			}
		/* SATHISH - END */	
		/* DHINESH - START */
		}else // FOR LEAVE ENTRY TABLE ARRAY
		if(array_key_exists($from_date,$check_leave_rlst) || array_key_exists($to_date,$check_leave_rlst))
		{
			$check_exist = 1;
			$message = "Already Leave Applied in this Date ..";
		}else// FOR ON DUTY ENTRY TABLE ARRAY
		if(array_key_exists($from_date,$check_on_duty_rlst) || array_key_exists($to_date,$check_on_duty_rlst)){
			$check_exist = 1;
			$message = "Already OD Applied in this Date ..";
		}
		// FOR LEAVE ENTRY TABLE
		unset($check_leave_rlst[$from_date]);
		unset($check_leave_rlst[$to_date]);

		// FOR ON DUTY ENTRY TABLE
		unset($check_on_duty_rlst[$from_date]);
		unset($check_on_duty_rlst[$to_date]);
		/* DHINESH - END */
		if(count($check_leave_rlst) > 0){
			$check_exist = 3;
			$message = "You are Already Leave Applied in Between From Date or To Date..";
		}else
		if(count($check_on_duty_rlst) > 0){
			$check_exist = 3;
			$message = "You are Already On Duty Applied in Between From Date or To Date..";
		}else{
			if((int)$check_exist > 0){
				if((int)$check_exist === 1){
					if((int)$from_leave_allow > 1){
						if((int)$from_leave_allow === (int)$from_date_type){
							$check_exist = 0;
						}else{
							$message = "Can Allow From date type $from_leave_allow ..";
						}
					}else{
						if((int)$check_request_type === 1){
							
							$message = "Already Leave Applied in this Date";
						}else
						if((int)$check_request_type === 3){
							$message = "Already OD Applied in this Date";
						}
					}
				}
				if((int)$check_exist === 2){
					if((int)$to_leave_allow > 1){
						if((int)$to_leave_allow === (int)$to_date_type){
							$check_exist = 0;
						}else{
							$message = "Can Allow To date type $to_leave_allow ..";
						}
					}else{
						if((int)$check_request_type === 1){
							$message = "Already Leave Applied in this Date";
						}else
						if((int)$check_request_type === 3){
							$message = "Already OD Applied in this Date";
						}
					} 
				}
			}
		}
		/* BSK same day leave can only allow different leave type  END */
		if((int)$check_exist > 0){
			echo json_encode(array('success' => TRUE, 'message' => "OOps..!! $message"));
		}
		// else
		// if($direct_leave_rlst){
		// 	$direct_leave_from_rlst  = array_reduce($direct_leave_rlst, function($result, $arr){	
		//     	$result[date("d-m-Y",strtotime($arr['from_date']))][] = $arr['from_date_type'];
		//     	return $result;
		// 	}, array());

		// 	$direct_leave_from_type  = array_reduce($direct_leave_rlst, function($result, $arr){		
		//     	$result[date("d-m-Y",strtotime($arr['from_date']))] = $arr['request_type'];
		//     	return $result;
		// 	}, array());

		// 	$direct_leave_to_rlst    = array_reduce($direct_leave_rlst, function($result, $arr){	
		//     	$result[date("d-m-Y",strtotime($arr['to_date']))][] = $arr['to_date_type'];
		//     	return $result;
		// 	}, array());

		// 	$direct_leave_to_type    = array_reduce($direct_leave_rlst, function($result, $arr){	
		//     	$result[date("d-m-Y",strtotime($arr['to_date']))] = $arr['request_type'];
		//     	return $result;
		// 	}, array());
		// 	//SK AND DK LEAVE ALLOW VALIDATION
		// 	$from_date_arr     = array();
		// 	$to_date_arr       = array();
		// 	$check_direct_type = "";

		// 	if(array_key_exists($from_date,$direct_leave_from_rlst) || array_key_exists($to_date,$direct_leave_from_rlst)){
		// 		if($direct_leave_from_rlst[$from_date]){
		// 			$from_date_arr[$from_date] = $direct_leave_from_rlst[$from_date][0];
		// 		}
		// 		if($direct_leave_from_rlst[$to_date]){				
		// 			$from_date_arr[$to_date]   = $direct_leave_from_rlst[$to_date][0];				
		// 		}			
		// 	}
		// 	if(array_key_exists($from_date,$direct_leave_to_rlst) || array_key_exists($to_date,$direct_leave_to_rlst)){
		// 		if($direct_leave_to_rlst[$from_date]){
		// 			if($direct_leave_to_rlst[$from_date][0] && $direct_leave_to_rlst[$from_date][1]){
		// 				$to_date_arr[$from_date]   = $direct_leave_to_rlst[$from_date][1];
		// 			}else{
		// 				$to_date_arr[$from_date]   = $direct_leave_to_rlst[$from_date][0];
		// 			}
					
		// 		}
		// 		if($direct_leave_to_rlst[$to_date]){
		// 			if($direct_leave_to_rlst[$to_date][0] && $direct_leave_to_rlst[$to_date][1]){
		// 				$to_date_arr[$to_date]     = $direct_leave_to_rlst[$to_date][1];
		// 			}else{
		// 				$to_date_arr[$to_date]     = $direct_leave_to_rlst[$to_date][0];
		// 			}				
		// 		}
		// 	}
		// 	$check_exist      = 0;
		// 	$from_leave_allow = 0;
		// 	$to_leave_allow   = 0;
		// 	$message          = "";
				
		// 	if(array_key_exists($from_date,$from_date_arr)){
		// 		if($from_date_arr[$from_date] === $from_date_type || $to_date_arr[$from_date] === $from_date_type || (int)$from_date_type === 1){
		// 			$check_exist = 1;	
					
		// 			if($to_date_arr[$from_date] === $from_date_type){
		// 				$check_direct_type  = $direct_leave_to_type[$from_date];
		// 			}
		// 			$check_direct_type      = $direct_leave_from_type[$from_date];				
		// 		}else{
		// 			if((int)$from_date_arr[$from_date] === 1){
		// 				$check_exist = 1;
		// 				$check_direct_type  = $direct_leave_from_type[$from_date];	
		// 			}else
		// 			if((int)$from_date_arr[$from_date] === 2){
		// 				$from_leave_allow = 3;
		// 				$check_exist = 1;
		// 			}else{
		// 				$from_leave_allow = 2;
		// 				$check_exist = 1;
		// 			}						
		// 		}	
		// 		// $message = "You are Already Leave Applied in this From Date..";
		// 	}else
		// 	/* SATHISH - START */
		// 	if(array_key_exists($from_date,$to_date_arr)){
		// 		if($from_date_arr[$from_date] === $from_date_type || (int)$from_date_arr[$from_date] === 1 || (int)$from_date_type === 1){
		// 			$check_exist        = 1;
		// 			$check_direct_type  = $direct_leave_from_type[$from_date];					
		// 		}else{
		// 			if((int)$to_date_arr[$from_date] === 1){
		// 				$check_exist        = 1;
		// 				$check_direct_type  = $direct_leave_to_type[$from_date];		
		// 			}else
		// 			if((int)$to_date_arr[$from_date] === 2){
		// 				$from_leave_allow = 3;
		// 				$check_exist = 1;
		// 			}else{
		// 				$from_leave_allow = 2;
		// 				$check_exist = 1;
		// 			}						
		// 		}	
		// 	}
		// 	/* SATHISH - END */

		// 	if(array_key_exists($to_date,$to_date_arr)){
		// 		if($from_date_arr[$to_date] === $to_date_type || $to_date_arr[$to_date] === $to_date_type || (int)$to_date_type === 1){
		// 			$check_exist = 2;
		// 			if($from_date_arr[$to_date] === $to_date_type){
		// 				$check_direct_type  = $direct_leave_from_type[$to_date];
		// 			}
		// 			$check_direct_type  = $direct_leave_to_type[$to_date];		
		// 		}else{
		// 			if((int)$to_date_arr[$to_date] === 1){
		// 				$check_exist = 2;
		// 				$check_direct_type  = $direct_leave_to_type[$to_date];		
		// 			}else
		// 			if((int)$to_date_arr[$to_date] === 2){
		// 				$to_leave_allow = 3;
		// 				$check_exist = 2;
		// 			}else{
		// 				$to_leave_allow = 2;
		// 				$check_exist = 2;
		// 			}		
		// 		}	
		// 		// $message = "You are Already Leave Applied in this To Date..";
		// 	}else
		// 	/* SATHISH - START */
		// 	if(array_key_exists($to_date,$from_date_arr)){
		// 		if($from_date_arr[$to_date] === $to_date_type || (int)$from_date_arr[$to_date] === 1 || (int)$to_date_type === 1){
		// 			$check_exist = 2;
		// 			$check_direct_type  = $direct_leave_from_type[$to_date];
		// 		}else{
		// 			if((int)$to_date_arr[$to_date] === 1){
		// 				$check_exist = 2;
		// 				$check_direct_type  = $direct_leave_to_type[$to_date];
		// 			}else
		// 			if((int)$to_date_arr[$to_date] === 2){
		// 				$to_leave_allow = 3;
		// 				$check_exist = 2;
		// 			}else{
		// 				$to_leave_allow = 2;
		// 				$check_exist = 2;
		// 			}		
		// 		}	
		// 	}
		// 		/* SATHISH - END */
		// 	// unset($check_leave_rlst[$from_date]);
		// 	// unset($check_leave_rlst[$to_date]);
		// 	// if(count($check_leave_rlst) > 0){
		// 	// 	$check_exist = 3;
		// 	// 	$message = "You are Already Leave Applied in Between From Date or To Date..";
		// 	// }else{
		// 		if((int)$check_exist > 0){
		// 			if((int)$check_exist === 1){
		// 				if((int)$from_leave_allow > 1){
		// 					if((int)$from_leave_allow === (int)$from_date_type){
		// 						$check_exist = 0;
		// 					}else{
		// 						$message = "Can Allow From date type $from_leave_allow ..";
		// 					}
		// 				}else{
		// 					if((int)$check_direct_type === 1){
		// 						$message = "Already Leave Applied in this Date ..";
		// 					}else
		// 					if((int)$check_direct_type === 3){
		// 						$message = "Already OD Applied in this Date ..";
		// 					}
		// 				}
		// 			}
		// 			if((int)$check_exist === 2){
		// 				if((int)$to_leave_allow > 1){
		// 					if((int)$to_leave_allow === (int)$to_date_type){
		// 						$check_exist = 0;
		// 					}else{
		// 						$message = "Can Allow To date type $to_leave_allow ..";
		// 					}
		// 				}else{
		// 					if((int)$check_direct_type === 1){
		// 						$message = "Already Leave Applied in this Date ..";
		// 					}else
		// 					if((int)$check_direct_type === 3){
		// 						$message = "Already OD Applied in this Date ..";
		// 					}
		// 				} 
		// 			}
		// 		}
		// 	// }
		// 	/* BSK same day leave can only allow different leave type  END */
		// 	if((int)$check_exist > 0){
		// 		echo json_encode(array('success' => TRUE, 'message' => "OOps..!! $message"));
		// 	}else{
		// 		if((int)$request_type === 1){
		// 			$leave_count = $this->total_no_of_days_count($component_value,$employee_code,$request_type,$leave_type,$from_date,$to_date,$from_date_type,$to_date_type,$prime_financial_id,$leave_balance);
		// 			echo json_encode(array('success' => FALSE, "leave_count"=>$leave_count));
		// 		}else{
		// 			echo json_encode(array('success' => FALSE));
		// 		}
		// 	}
		// }
		else{
			if((int)$request_type === 1){
				$leave_count = $this->total_no_of_days_count($component_value,$employee_code,$request_type,$leave_type,$from_date,$to_date,$from_date_type,$to_date_type,$prime_financial_id,$leave_balance);
				echo json_encode(array('success' => FALSE, "leave_count"=>$leave_count));
			}else{
				echo json_encode(array('success' => FALSE));
			}	
		}
	}	
	
	public function total_no_of_days_count($component_value,$employee_code,$request_type,$leave_type,$from_date,$to_date,$from_date_type,$to_date_type,$prime_financial_id,$leave_balance){		
		$total_leave         = "";
		$from_date_diff      = strtotime($from_date);
		$to_date_diff        = strtotime($to_date);
		$datediff            = $to_date_diff - $from_date_diff;
		$no_of_days          = round($datediff / (60 * 60 * 24));
		$holiday_result      = array();
		$weekoff_result      = array();

		if((int)$request_type === 1 || (int)$request_type === 2 || (int)$request_type === 3 || (int)$request_type === 8){
			$startTimeStamp  = strtotime($from_date);
			$endTimeStamp    = strtotime($to_date);
			$timeDiff        = abs($endTimeStamp - $startTimeStamp);
			$numberDays      = $timeDiff/86400;  // 86400 seconds in one day
			// and you might want to convert to integer
			$numberDays      = intval($numberDays);
			$numberDays      = (int)$numberDays + 1;
			$date_range      = $this->getDatesFromRange($from_date, $to_date);
			$get_year        = date('Y',strtotime($from_date));

			//for Get Leave Creation
			$leave_creation_qry    = 'SELECT count(*) as creation_count,intervening_holidays,intervening_type,leave_name,coff from cw_leave_creation where cw_leave_creation.trans_status = 1 and prime_leave_creation_id = "'.$leave_type.'"';
			$leave_creation_info   = $this->db->query("CALL sp_a_run ('SELECT','$leave_creation_qry')");
			$leave_creation_result = $leave_creation_info->result();
			$leave_creation_info->next_result();		
			$intervening_holidays  = $leave_creation_result[0]->intervening_holidays;
			$intervening_type      = explode(",",$leave_creation_result[0]->intervening_type);
			$leave_name  		   = $leave_creation_result[0]->leave_name;
			$leave_name 		   = strtolower($leave_name);
			$creation_count 	   = $leave_creation_result[0]->creation_count;
			$coff 	               = $leave_creation_result[0]->coff;
			$pending_column 	   = "pending_".$leave_name;

			//SELECT QUERY FOR CHECK A GENENRAL SETTING PARAMETER BASED TYPE
			$param_based_type_qry  = 'SELECT parameter_type,based_on FROM cw_general_setting inner join cw_parameter_type on cw_parameter_type.prime_parameter_type_id = cw_general_setting.entry_parameter_type WHERE cw_general_setting.trans_status = 1';
			$param_based_type_info = $this->db->query("CALL sp_a_run ('SELECT','$param_based_type_qry')");
			$param_based_type_rslt = $param_based_type_info->result_array();
			$param_based_type_info->next_result();

			$param_based_type_arr  = array_reduce($param_based_type_rslt, function($result, $arr){			
		    $result[$arr['parameter_type']] = $arr['based_on'];
		    return $result;
			}, array());
			$week_off_entry        = (int)$param_based_type_arr['Weekly off Entry'];	
			$holiday_entry         = (int)$param_based_type_arr['Holiday Entry'];	
			$leave_entry           = (int)$param_based_type_arr['Leave Entry'];	

			//CONDITION FOR CHECK A HOLIDAY DATE FOR PARAMETER TYPE BASED ON
			if($holiday_entry === 2){
				$holid_component_query  = 'SELECT label_name,components FROM cw_general_setting inner join cw_form_setting on cw_form_setting.prime_form_id = cw_general_setting.components WHERE entry_parameter_type = 2 and cw_general_setting.trans_status = 1';
				$holid_component_info   = $this->db->query("CALL sp_a_run ('SELECT','$holid_component_query')");
				$holid_component_result = $holid_component_info->result();
				$holid_component_info->next_result();	
			
				$holid_label_name    = $holid_component_result[0]->label_name;
				//$holid_comp_value    = $this->emp_pick_arr[$employee_code][$holid_label_name];
				$emp_pick_arr        = $this->get_emp_data();
				$holid_comp_value    = $emp_pick_arr[$employee_code][$holid_label_name];
				$holiday_qry  = 'select cw_holiday_entry_holiday_data.holiday_date from cw_holiday_entry inner join cw_holiday_entry_holiday_data on cw_holiday_entry_holiday_data.prime_holiday_entry_id = cw_holiday_entry.prime_holiday_entry_id where FIND_IN_SET("'.$holid_comp_value.'", cw_holiday_entry_holiday_data.component_value) and cw_holiday_entry.holiday_year = "'.$get_year.'" and cw_holiday_entry.trans_status = 1 and cw_holiday_entry_holiday_data.trans_status = 1';
				$holiday_info   = $this->db->query("CALL sp_a_run ('SELECT','$holiday_qry')");
				$holiday_result    = $holiday_info->result_array();
				$holiday_info->next_result();		
				$holiday_result = array_reduce($holiday_result, function($result, $arr){			
				    $result[$arr['holiday_date']] = $arr;
				    return $result;
				}, array());
			}
			//CONDITION FOR CHECK A WEEKOFF DATE FOR PARAMETER TYPE BASED ON
			//echo $week_off_entry; die;
			if($week_off_entry === 1){
				$check_weekoff_qry   = 'SELECT employee_code,weekoff_date,weekoff_type from cw_weekoff_import WHERE employee_code = "'. $employee_code .'" and weekoff_date >= (date_format(str_to_date("'.$from_date.'", "%d-%m-%Y") , "%Y-%m-%d")) and weekoff_date <= (date_format(str_to_date("'.$to_date.'", "%d-%m-%Y") , "%Y-%m-%d")) and financial_setting_id = '.$prime_financial_id.' and trans_status = 1';
				$check_weekoff_info   = $this->db->query("CALL sp_a_run ('SELECT','$check_weekoff_qry')");
				$check_weekoff_rlst   = $check_weekoff_info->result_array();
				$check_weekoff_info->next_result();

				$weekoff_result       = array_reduce($check_weekoff_rlst, function($result, $arr){			
				    $result[$arr['employee_code']][$arr['weekoff_date']] = $arr['weekoff_type'];
				    return $result;
					}, array());
			}else
			if($week_off_entry === 2){
				//QUERY AND CODE ARE USED FOR GET A WEEK OFF AND HOLIDAY DETAILS
				$week_component_query  = 'SELECT label_name,components FROM cw_general_setting inner join cw_form_setting on cw_form_setting.prime_form_id = cw_general_setting.components WHERE entry_parameter_type = 1 and cw_general_setting.trans_status = 1';
				$week_component_info   = $this->db->query("CALL sp_a_run ('SELECT','$week_component_query')");
				$week_component_result = $week_component_info->result();
				$week_component_info->next_result();

				$week_label_name       = $week_component_result[0]->label_name;
				//$week_comp_value       = $this->emp_pick_arr[$employee_code][$week_label_name];
				$emp_pick_arr          = $this->get_emp_data();
				$week_comp_value       = $emp_pick_arr[$employee_code][$week_label_name];
				/* Weekoff - START */
				$weekoff_qry = 'select cw_weekoff_entry_weekoff_days_details.weekday,cw_weekoff_entry_weekoff_days_details.first_week,cw_weekoff_entry_weekoff_days_details.second_week,cw_weekoff_entry_weekoff_days_details.third_week,cw_weekoff_entry_weekoff_days_details.fourth_week,cw_weekoff_entry_weekoff_days_details.fifth_week from cw_weekoff_entry inner join cw_weekoff_entry_weekoff_days_details on cw_weekoff_entry_weekoff_days_details.prime_weekoff_entry_id = cw_weekoff_entry.prime_weekoff_entry_id where FIND_IN_SET("'.$week_comp_value.'", cw_weekoff_entry.component_value) and cw_weekoff_entry.from_date <= (date_format(str_to_date("'.$from_date.'", "%d-%m-%Y") , "%Y-%m-%d")) AND cw_weekoff_entry.to_date >= (date_format(str_to_date("'.$to_date.'", "%d-%m-%Y") , "%Y-%m-%d")) and cw_weekoff_entry.trans_status = 1 and cw_weekoff_entry_weekoff_days_details.trans_status = 1';
				$weekoff_info   = $this->db->query("CALL sp_a_run ('SELECT','$weekoff_qry')");
				$weekoff_result    = $weekoff_info->result_array();
				$weekoff_info->next_result();
				$weekoff_result = array_reduce($weekoff_result, function($result, $arr){		
				    $result[$arr['weekday']] = $arr;
				    return $result;
				}, array());
				
				/* Weekoff - END */
				$days_arr = array("sun"=>1,"mon"=>2,"tue"=>3,"wed"=>4,"thu"=>5,"fri"=>6,"sat"=>7);
				$week_arr = array(1=>"first_week",2=>"second_week",3=>"third_week",4=>"fourth_week",5=>"fifth_week");
			}

			$from_date_count  = 0;
			$to_date_count    = 0;
			if(!$leave_balance){
				$leave_balance =10;
			}

			//intervening holidays check for before from date
			if((int)$intervening_holidays === 1 && in_array("1",$intervening_type)){
				//echo "BSK";
				for($j=1;$j<=(int)$leave_balance;$j++){
					$date          = new DateTime($from_date);
					$date->modify("-$j day");
					$check_prev    = $date->format("Y-m-d");
					//WEEKOFF DATE CHECK					
					if($week_off_entry === 1){
						$weekoff_value = (int)$weekoff_result[$employee_code][$check_prev];		
					}else
					if($week_off_entry === 2){
						$get_day       = strtolower(date('D',strtotime($check_prev)));
						$day           = $days_arr[$get_day];
						$week_no       = $this->weekOfMonth(strtotime($check_prev)); 
						$week          = $week_arr[$week_no];
						$weekoff_value = $weekoff_result[$day][$week];	
					}
					//HOLIDAY DATE CHECK
					if($holiday_entry === 2){
						$prev_holiday  = $holiday_result[$check_prev]['holiday_date'];
					}	
					if($prev_holiday ||  $weekoff_value){
						$from_date_count = $from_date_count + 1;					
					}else{
						break;
					}									
				}
			}
			//intervening holidays check for after to date
			if((int)$intervening_holidays === 1 && in_array("2",$intervening_type)){
				//Check after todate
				for($i=1;$i<=(int)$leave_balance;$i++){			
					$after_date = new DateTime($to_date);
					$after_date->modify("$i day");
					$check_after = $after_date->format("Y-m-d");

					//WEEKOFF DATE CHECK
					if($week_off_entry === 1){
						$after_weekoff_value = (int)$weekoff_result[$employee_code][$check_after];		
					}else
					if($week_off_entry === 2){
						$get_after_day       = strtolower(date('D',strtotime($check_after)));
						$after_day           = $days_arr[$get_after_day];
						$after_week_no       = $this->weekOfMonth(strtotime($check_after)); 
						$after_week          = $week_arr[$after_week_no];
						$after_weekoff_value = $weekoff_result[$after_day][$after_week];		
					}
					//HOLIDAY DATE CHECK
					if($holiday_entry === 2){
						$after_holiday  = $holiday_result[$check_after]['holiday_date'];
					}	
					if($after_holiday || $after_weekoff_value){
						$to_date_count = $to_date_count + 1;
					}else{
						break;
					}	
				}	
			}	
			//print_r($weekoff_result); die;
			$end_key       = end(array_keys($date_range));
			$leave_count   = 0;
			$total_leave   = 0;
			foreach ($date_range as $key => $common_date){
				//WEEKOFF DATE CHECK
				if($week_off_entry === 1){
					$weekoff_value      = (int)$weekoff_result[$employee_code][$common_date];		
				}else
				if($week_off_entry === 2){
					$get_day            = strtolower(date('D',strtotime($common_date)));
					//Check weekoff day exist
					$day                = $days_arr[$get_day];
					$week_no            = $this->weekOfMonth(strtotime($common_date)); 
					$week               = $week_arr[$week_no];
					$weekoff_value      = $weekoff_result[$day][$week];		
				}
				//HOLIDAY DATE CHECK
				if($holiday_entry === 2){
					$get_common_holiday = $holiday_result[$common_date]['holiday_date'];
				}	
				
				if($key === 0){
					if((int)$from_date_type === 1){
						$leave_count = 1.00;
					}else
					if((int)$from_date_type === 2 || (int)$from_date_type === 3){
						$leave_count = 0.50;
					}
				}else
				if($key === $end_key){
					if((int)$to_date_type === 1){
						$leave_count = 1.00;
					}else
					if((int)$to_date_type === 2 || (int)$to_date_type === 3){
						$leave_count = 0.50;
					}
				}else{
					//intervening holidays check for between dates
					// if((int)$intervening_holidays === 1){
					//echo "BSK $weekoff_value :: $get_common_holiday :: $intervening_holidays"; die;
					if((int)$weekoff_value === 1 || $get_common_holiday){
						if((int)$intervening_holidays === 1 && in_array("3",$intervening_type)){
							$leave_count = 1.00;
						}else{
							$leave_count = 0;
						}						
					}else
					if((int)$weekoff_value === 2 && ((int)$intervening_holidays === 1 && in_array("3",$intervening_type))){
						$leave_count = 0.50;
					}else
					if((int)$weekoff_value === 3 && ((int)$intervening_holidays === 1 && in_array("3",$intervening_type))){
						$leave_count = 0.50;
					}else{
						$leave_count = 1.00;
					}
				}
				$total_leave = $total_leave + $leave_count;
			}
			$total_leave = $total_leave + $from_date_count + $to_date_count;
			return $total_leave;
		}
	}

	//DR CODE START FOR PERMISSION REQUEST 
	public function permission_request(){
		$encString           = file_get_contents('php://input');
		$_POST               = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Url Expired.. Please refresh the page and try again....','table_data' => ""));
			exit(0);
		}
		$component_value     = $this->input->post('component_value');
		if($this->config->item("db_name") === 'tcl_hrms' || $this->config->item("db_name") === 'tcl_dev'){
			$employee_code   = $this->input->post('employee_code');
		}else{
			$employee_code   = $this->session->userdata('logged_emp_code');
		}
		$permission_date     = date("Y-m-d",strtotime($this->input->post('permission_date')));
		$shift_name          = $this->input->post('shift_name');
		$in_time             = $this->input->post('in_time');
		$out_time            = $this->input->post('out_time');
		$total_time          = $this->input->post('total_time');
		$permission_type     = $this->input->post('permission_type');
		$financial_info      = $this->get_leave_financial_details();
		$financial_year_id   = $financial_info[0]->prime_leave_financial_year_id;
		//TIME CONVERT TO MINUTES 
		$total_time_arr      = explode(':', $total_time);
    	$total_time          = round(($total_time_arr[0]*60) + ($total_time_arr[1]));

    	$per_setting_check   = $this->permission_setting_check($component_value,$employee_code,$permission_date,$shift_name,$in_time,$out_time,$total_time,$permission_type);
    	if($per_setting_check){
    		echo json_encode(array('success' => TRUE, 'message' => "proceed"));
    	}
	}

	//for get shift name 
	public function get_shift_name(){
		$encString           = file_get_contents('php://input');
		$_POST               = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Url Expired.. Please refresh the page and try again....','table_data' => ""));
			exit(0);
		}
		if($this->config->item("db_name") === 'tcl_hrms' || $this->config->item("db_name") === 'tcl_dev'){
			$employee_code   = $this->input->post('employee_code');
		}else{
			$employee_code   = $this->session->userdata('logged_emp_code');
		}
		$shift_date         = date("Y-m-d",strtotime($this->input->post('shift_date')));
		$financial_info      = $this->get_leave_financial_details();
		$financial_year_id   = $financial_info[0]->prime_leave_financial_year_id;
		$shift_import_qry   = 'SELECT shift_name FROM cw_shift_import WHERE cw_shift_import.employee_code = "'.$employee_code.'" and cw_shift_import.shift_date = "'.$shift_date.'" and cw_shift_import.financial_setting_id= "'.$financial_year_id.'" and cw_shift_import.trans_status = 1';
		$shift_import_info  = $this->db->query("CALL sp_a_run ('SELECT','$shift_import_qry')");
		$shift_import_rslt  = $shift_import_info->result();
		$shift_import_info->next_result();	
		$shift_name         = $shift_import_rslt[0]->shift_name;		
		if($shift_name){
			echo json_encode(array('success' => TRUE, 'shift_name' => $shift_name));
		}else{
			echo json_encode(array('success' => FALSE, 'message' => "Shift not Allocated for this Date Please Contact Admin.!"));
		}
	}
	
	//Check Coff exist for the leave date
	public function check_coff_exist($employee_code,$prime_financial_id,$from_date){
		//and financial_setting_id = "'.$prime_financial_id.'" Commented by BSK
		$coff_entry_qry      = 'select SUM(balance_count) as coff_count from cw_coff_entry where employee_code = "'.$employee_code.'" and credited_date <= "'.$from_date.'" and trans_status = 1 and coff_status = 1';
			$coff_entry_info     = $this->db->query("CALL sp_a_run ('SELECT','$coff_entry_qry')");
			$coff_entry_result   = $coff_entry_info->result();
			$coff_entry_info->next_result();
			$coff_count    = $coff_entry_result[0]->coff_count;
			if(!$coff_count){
				$coff_count = 0;
			}
			return $coff_count;
	}		
}
?>