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/cloud_cafsinfotech_in/application/controllers/Leave_credit_manual.php
<?php if ( ! defined('BASEPATH')) exit('No direct script is allowed');
require_once("Action_controller.php");
class Leave_credit_manual  extends Action_controller{	
	public function __construct(){
		parent::__construct('leave_credit_manual');
	}
	
	// LOAD PAGE QUICK LINK,FILTERS AND TABLE HEADERS
	public function index(){
		//GET A COMPONENT ARRAY
		$get_components_qry     = 'select prime_form_id,prime_module_id,label_name,view_name from `cw_form_setting` where prime_module_id = "employees" and field_type = 5 ORDER BY label_name';
		$get_components_info    = $this->db->query("CALL sp_a_run ('SELECT','$get_components_qry')");
		$get_components_result  = $get_components_info->result();
		$get_components_info->next_result();	
		$components_arr         = array();
		foreach($get_components_result as $component){
			$prime_form_id                  = $component->prime_form_id;
			$components_name                = strtolower($component->view_name);
			$components_arr[$prime_form_id] = $components_name;	
		}
		$data['components_arr'] = $components_arr;
		//COMPONENT VALUE ARRAY
		$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);
		}	
		$data['components']      = $components;
		$data['component_value'] = array("" => "---- Select Column ----") + $final_pick;
		// //DR CODE FOR HIDE A ADD BUTTON AND EDIT BUTTON
		$this->load->view("$this->control_name/manage",$data);
	}
	public function manual_leave_credit(){
		$start_time                = date("Y-m-d H:i:s");
		$process_month             = $this->input->post('process_month');
		$process_mon_year          = date("Y-m",strtotime("01-".$process_month));
		$financial_info            = $this->get_leave_financial_details();
		$fin_year_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));
		$check_month               = date('m-Y',strtotime("+1 month",strtotime("01-".$process_month)));
		$fin_start_month           = date("Y-m",strtotime( $financial_info[0]->starting_date));
		$fin_end_month             = date("Y-m",strtotime( $financial_info[0]->ending_date));

		//CHECK IF PROCESS MONTH IS ONLY A CURRENT FINANCIAL YEAR OR NOT
		if($process_mon_year > $fin_end_month){
			echo json_encode(array('success' => FALSE, 'message' => "Future Financial Year not Allowed!!"));
	        exit(0);
		}else
		if($process_mon_year < $fin_start_month){
			echo json_encode(array('success' => FALSE, 'message' => "Past Financial Year not Allowed!!"));
	        exit(0);
		}

		//CHECK LOG EXISTS FOR CHECK THIS PROCESS MONTH
		$cr_month_log_exist_qry    = 'SELECT count(employee_code) as exist_count FROM cw_leave_cr_upd_log WHERE leave_financial_id = "'.$fin_year_id.'" and entry_month = "'.$check_month.'"  order by employee_code asc limit 0,1';
		$cr_month_log_exist_info   = $this->db->query("CALL sp_a_run ('SELECT','$cr_month_log_exist_qry')");
		$cr_month_log_exist_result = $cr_month_log_exist_info->result();
		$cr_month_log_exist_info->next_result();
		$cr_month_log_exist        = (int)$cr_month_log_exist_result[0]->exist_count;

		//FOR CHECK A LEAVE POSTING LOCK
		if($cr_month_log_exist){
			echo json_encode(array('success' => FALSE, 'message' => "Past Month not Allowed!!"));
	        exit(0);
		}else{
			//IF PAYROLL POSTING LOCK OR NOT FOR THIS PROCESS MONTH
			$check_lock_count      = $this->check_posting_lock($process_month);
	        if((int)$check_lock_count > 0){
	        	echo json_encode(array('success' => FALSE, 'message' => "Payroll Posting Locked for This Month!!"));
	        	exit(0);
	        }
	    }
		//Get Salary Start Date and End Date
		$month_day_qry             = 'select category,day_conditions,day_count,day_start,day_end from cw_month_day where cw_month_day.trans_status = 1';
		$month_day_data            = $this->db->query("CALL sp_a_run ('SELECT','$month_day_qry')");
		$month_day_result          = $month_day_data->result_array();
		$month_day_data->next_result();
		$month_day_result          = array_reduce($month_day_result, function ($result, $arr) {
		    $result[$arr['category']] = $arr;
		    return $result;
			}, array());

		//GET DATA FROM A GENERAL SETTING TABLE
		$general_setting_qry       = 'SELECT components FROM cw_general_setting WHERE entry_parameter_type = "3" and cw_general_setting.trans_status = 1';
		$general_setting_info      = $this->db->query("CALL sp_a_run ('SELECT','$general_setting_qry')");
		$general_setting_result    = $general_setting_info->result();
		$general_setting_info->next_result();
		$component_id              = $general_setting_result[0]->components;

		//TO GET ALL PICKLIST DATA FROM A EMPLOYEE MASTER 
		$get_components_qry        = 'select prime_form_id,prime_module_id,label_name,view_name from `cw_form_setting` where prime_module_id = "employees" and field_type = 5 ORDER BY label_name';
		$get_components_info       = $this->db->query("CALL sp_a_run ('SELECT','$get_components_qry')");
		$get_components_result     = $get_components_info->result();
		$get_components_info->next_result();
		$components                = array();
		foreach($get_components_result as $component){
			$prime_form_id              = $component->prime_form_id;
			$components_name            = strtolower($component->view_name);
			$components[$prime_form_id] = $components_name;	
		}
		$component_name                 =    $components[$component_id];
		if($component_name === "category"){
			$component_name             = "role";
		}
		$prime_table_query = 'SELECT leave_name FROM cw_leave_creation WHERE trans_status = 1 and leave_opening = 1';
		$columns_info      = $this->db->query("CALL sp_a_run ('SELECT','$prime_table_query')");
		$columns           = $columns_info->result();
		$columns_info->next_result();
		$select_columns    = "";
		foreach ($columns as $key => $value) {
			$leave_name    =  strtolower($value->leave_name);
			if($leave_name){
				$select_columns .= $leave_name."_credit".",(".$leave_name."_credit+".$leave_name.") as tot_".$leave_name.",";
			}			
		}
		$select_columns       = rtrim($select_columns,",");
		//EMPLOYEE CREDIT LEAVE SETTING QUERY
		$leave_credit_qry     = 'SELECT LOWER(cw_leave_creation.leave_name) as leave_name,cw_leave_credit_setting.component_value,cw_leave_credit_setting.category as components,entry_type,manual_credit_type,credit_based_on,eligible_days,credit_days,prime_leave_credit_setting_id FROM cw_leave_credit_setting inner join cw_leave_creation on cw_leave_creation.prime_leave_creation_id = cw_leave_credit_setting.leave_name WHERE cw_leave_credit_setting.leave_financial_year = "'. $fin_year_id .'" and cw_leave_credit_setting.trans_status = 1';
		$leave_credit_info    = $this->db->query("CALL sp_a_run ('SELECT','$leave_credit_qry')");
		$leave_credit_result  = $leave_credit_info->result_array();
		$leave_credit_info->next_result();		
		//LEAVE OPENING ARRAY
		$leave_credit_arr     = "";
		if(empty($leave_credit_result[0])){
			echo json_encode(array('success' => FALSE, 'message' => "Leave Credit Setting Module should not be Empty Please Contact Admin!!"));
	        exit(0);
		}else{	
			if($leave_credit_result){
				$leave_credit_arr = array_reduce($leave_credit_result, function ($result, $arr) {
			    $result[$arr['component_value']][$arr['leave_name']] = $arr;
			    return $result;
				}, array());
			}		
	
			$credit_components    = implode(",",array_keys($leave_credit_arr));

			//EMPLOYEE LEAVE OPENING QUERY
			$leave_opening_qry    = 'SELECT '.$select_columns.',employee_code,component_value FROM cw_leave_opening WHERE cw_leave_opening.financial_setting_id = "'.$fin_year_id.'" and cw_leave_opening.trans_status = 1 and component_value in ('.$credit_components.')';
			$leave_opening_info   = $this->db->query("CALL sp_a_run ('SELECT','$leave_opening_qry')");
			$leave_opening_result = $leave_opening_info->result_array();
			$leave_opening_info->next_result();		
			//LEAVE OPENING ARRAY
			$leave_opening_arr    = "";
			if($leave_opening_result){
				$leave_opening_arr = array_reduce($leave_opening_result, function ($result, $arr) {
			     $result[$arr['component_value']][$arr['employee_code']] = $arr;
			    return $result;
				}, array());
			}

			$before_joining_result = $this->month_wise($leave_credit_arr,$leave_opening_arr,$component_name,$fin_year_id,$fin_start_date,$fin_end_date,$credit_components,$month_day_result,$start_time,$process_month);
			if($before_joining_result){
				return true;
			}else{
				return false;
			}
		}
	}
	public function month_wise($leave_credit_arr,$leave_opening_arr,$component_name,$fin_year_id,$fin_start_date,$fin_end_date,$credit_components,$month_day_result,$start_time,$process_month){
		$fin_start_month      = date("Y-m", strtotime($fin_start_date));
		$cur_year             = date("Y");
		$check_month_val      = date("n",strtotime("01-".$process_month));
		$prev_month_cr_check  = date("m-Y", strtotime("-1 month" , strtotime("01-".$process_month)));
		//GET Date Columns
		$date_columns_qry     = 'select GROUP_CONCAT(label_name) as label_name from cw_form_setting where prime_module_id = "employees" and  field_type = 4 and input_for not in (38,40,111) and trans_status = 1';
		$date_columns_data    = $this->db->query("CALL sp_a_run ('SELECT','$date_columns_qry')");
		$date_columns_result  = $date_columns_data->result();
		$date_columns_data->next_result();
		$label_names          = $date_columns_result[0]->label_name;

		//EMPLOYEE DETAILS QRY
		$emp_qry              = 'SELECT '.$component_name.' as component_name,cw_employees.role as category,cw_employees.employee_code,'.$label_names.' FROM cw_employees WHERE cw_employees.trans_status = 1 and '.$component_name.' in ('.$credit_components.')';
		$emp_info             = $this->db->query("CALL sp_a_run ('SELECT','$emp_qry')");
		$emp_result           = $emp_info->result_array();
		$emp_info->next_result();
		
		//EMPLOYEE DETAILS ARRAY
		$emp_result_arr       = "";
		if($emp_result){
			$emp_result_arr   = array_reduce($emp_result, function ($result, $arr) {
		     $result[$arr['component_name']][$arr['employee_code']] = $arr;
		    return $result;
			}, array());
		}

		//FOR CHECK A PREVIOUS MONTH TO BE CREDIT UPDATE OR NOT IF CR UPDATE LOG COUNT IS ABOVE 0 TO CHECK THIS BELOW NEXT QUERY
		$cr_log_exist_qry           = 'SELECT count(employee_code) as exist_count FROM cw_leave_cr_upd_log WHERE leave_financial_id = "'.$fin_year_id.'" order by employee_code asc limit 0,1';
		$cr_log_exist_info          = $this->db->query("CALL sp_a_run ('SELECT','$cr_log_exist_qry')");
		$cr_log_exist_result        = $cr_log_exist_info->result();
		$cr_log_exist_info->next_result();
		$cr_log_exist               = (int)$cr_log_exist_result[0]->exist_count;

		
		if($cr_log_exist){
			$cr_prev_mon_log_qry    = 'SELECT count(employee_code) as count FROM cw_leave_cr_upd_log WHERE cw_leave_cr_upd_log.entry_month = "'.$prev_month_cr_check.'" order by employee_code asc limit 0,1';
			$cr_prev_mon_log_info   = $this->db->query("CALL sp_a_run ('SELECT','$cr_prev_mon_log_qry')");
			$cr_prev_mon_log_result = $cr_prev_mon_log_info->result();
			$cr_prev_mon_log_info->next_result();
 
			$prev_month_exist       = $cr_prev_mon_log_result[0]->count;
			//This cond not check for Fin Start Year
			if($fin_start_month !== date("Y-m",strtotime("01-".$process_month))){
				if(!$prev_month_exist){
					echo json_encode(array('success' => FALSE, 'message' => "Mnaual Credit not Updated to Prevoius Month?"));
					exit(0);
				}
			}
		}
		
		//QUERY AND ARRAY FOR CHECK ALREADY THIS PROCESS MONTH CREDIT UPDATED OR NOT
		$cr_log_qry          = 'SELECT component_value,entry_month,employee_code,leave_name FROM cw_leave_cr_upd_log WHERE cw_leave_cr_upd_log.entry_month = "'.$process_month.'"';
		$cr_log_info         = $this->db->query("CALL sp_a_run ('SELECT','$cr_log_qry')");
		$cr_log_result       = $cr_log_info->result_array();
		$cr_log_info->next_result();
		
		//EMPLOYEE lEAVE CREDIT ARRAY
		$cr_log_arr          = "";
		$cr_month_type_arr   = "";
		if($cr_log_result){
			$cr_log_arr      = array_reduce($cr_log_result, function ($result, $arr) {
		     $result[$arr['employee_code']][$arr['entry_month']][$arr['leave_name']] = $arr;
		    return $result;
			}, array());
		}	

		//QUERY FOR MONTH TYPE VALIDATION CHECK LIKE QUARTERLY,YEARLY WISE
		$cr_month_type_qry    = 'SELECT component_value,entry_month,employee_code,leave_name FROM cw_leave_cr_upd_log WHERE cw_leave_cr_upd_log.leave_financial_id = "'.$fin_year_id.'"';
		$cr_month_type_info   = $this->db->query("CALL sp_a_run ('SELECT','$cr_month_type_qry')");
		$cr_month_type_result = $cr_month_type_info->result_array();
		$cr_month_type_info->next_result();

		if($cr_month_type_result){
			$cr_month_type_arr   = array_reduce($cr_month_type_result, function ($result, $arr) {
				$year            = explode("-",$arr['entry_month']);
		     $result[$arr['employee_code']][$year[1]][$arr['leave_name']] = $arr;
		    return $result;
			}, array());
		}	
		$insert_qry          = "";
		//START PROCESS
		if($leave_credit_arr){
			foreach($leave_credit_arr as $key => $leave_arr){ //key is a component value					
				$emp_details      = $emp_result_arr[$key];				
				foreach($emp_details as $emp_code => $emp_value){
					$category         = $emp_value['category'];
					//Get Salary Start Date
					if($category){
						$month_day_arr = $month_day_result[$category];
						if($month_day_arr){
							$day_conditions = $month_day_arr['day_conditions'];
							$day_count      = $month_day_arr['day_count'];
							$day_start      = $month_day_arr['day_start'];
							$day_end        = $month_day_arr['day_end'];
							if((int)$day_conditions === 3){
								$sal_start = $day_start;
								//For Current month between days increment
								$date              = new DateTime("01-$process_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."-".$process_month));
							}else{
								$sal_start         = '01';
								$date              = new DateTime("01-$process_month 00:00:00");
								$salary_start_date = $date->format("Y-m-$sal_start");	
								$salary_end_date   = date("Y-m-d",strtotime($day_end."-".$process_month));
								if((int)$day_conditions === 2){
									$day_end = date("t");
								}
							}
						}
					}
					$upd_qry    = "";					
					$ins_key    = "";	
					$ins_val    = "";													
					foreach($leave_arr as $leave_name_key => $leave_name_value){ // leave name
						$leave_name          = $leave_name_value['leave_name'];
						$components          = $leave_name_value['components'];
						$component_value     = $leave_name_value['component_value'];
						$eligible_days       = $leave_name_value['eligible_days'];
						$credit_based_on     = $leave_name_value['credit_based_on'];
						$credit_days         = $leave_name_value['credit_days'];
						$entry_type          = $leave_name_value['entry_type'];
						$manual_credit_type  = (int)$leave_name_value['manual_credit_type'];
						$cr_setting_id       = $leave_name_value['prime_leave_credit_setting_id'];	
						$based_on_date       = $emp_value[$credit_based_on];		

						if($leave_opening_arr[$component_value][$emp_code]){
							$total_credit    = $leave_opening_arr[$component_value][$emp_code]['tot_'.$leave_name];
							$prev_credit     = $leave_opening_arr[$component_value][$emp_code][$leave_name."_credit"];
						}else{
							$total_credit    = 0;
							$prev_credit     = 0;
						}						
						$final_credit        = $total_credit + $credit_days;
						$check_date          = "";
						if($final_credit <= $eligible_days){
							//Log Already Exist for this Financial Year
							if (!array_key_exists($leave_name,$cr_log_arr[$emp_code][$process_month])){
								if($cr_log_exist === 0){ 
									if($manual_credit_type === 1){						
										if($based_on_date <= $fin_start_date){//Joined Before Fin Year
											$check_date = $fin_start_date;
										}else //Joined Between Fin Year
										if(($based_on_date > $fin_start_date) && ($based_on_date <= $salary_end_date)){
											$check_date = $based_on_date;
										}
									}else
									if($manual_credit_type === 2){

										if($based_on_date <= $fin_start_date){//Joined Before Fin Year
											$check_date      = $fin_start_date;
										}else //Joined Between Fin Year
										if(($based_on_date > $fin_start_date) && ($based_on_date <= $salary_end_date)){
											$check_date      = $based_on_date;
										}
										if((int)$check_month_val <= 3){
											$salary_end_date = "$day_end-03-$cur_year";
										}else
										if((int)$check_month_val <= 6){
											$salary_end_date = "$day_end-06-$cur_year";
										}else
										if((int)$check_month_val <= 9){
											$salary_end_date = "$day_end-09-$cur_year";
										}else
										if((int)$check_month_val <= 12){
											$salary_end_date = "$day_end-12-$cur_year";
										}
									}else
									if($manual_credit_type === 3){
										if($based_on_date <= $fin_start_date){//Joined Before Fin Year
											$check_date      = $fin_start_date;
										}else //Joined Between Fin Year
										if(($based_on_date > $fin_start_date) && ($based_on_date <= $salary_end_date)){
											$check_date      = $based_on_date;
										}
										if((int)$check_month_val <= 6){
											$salary_end_date = "$day_end-06-$cur_year";
										}else
										if((int)$check_month_val <= 12){
											$salary_end_date = "$day_end-12-$cur_year";
										}
									}else
									if($manual_credit_type === 4){
										if($based_on_date <= $fin_start_date){//Joined Before Fin Year
											$check_date      = $fin_start_date;
										}else //Joined Between Fin Year
										if(($based_on_date > $fin_start_date) && ($based_on_date <= $salary_end_date)){
											$check_date      = $based_on_date;
										}
										if((int)$check_month_val <= 12){
											$salary_end_date = "$day_end-12-$cur_year";
										}
									}
								}else{
									if($manual_credit_type === 1){	
										if($based_on_date === $salary_start_date){ //Joined Before Fin Year
											$check_date      = $salary_start_date;
										}else //Joined Between Fin Year
										if(($based_on_date > $salary_start_date) && ($based_on_date < $salary_end_date)){
											$check_date      = $based_on_date;
										}
									}else
									if($manual_credit_type === 2){
										if($based_on_date <= $salary_start_date){ //Joined Before Fin Year
											$check_date      = $salary_start_date;
										}else //Joined Between Fin Year
										if(($based_on_date > $salary_start_date) && ($based_on_date < $salary_end_date)){
											$check_date      = $based_on_date;
										}
										$check_month_valid   = ($check_month_val-1)/3;

										if(is_int($check_month_valid) || (!array_key_exists($leave_name,$cr_month_type_arr[$emp_code][$cur_year]))){

											//IF PROCESS MONTH 3,6,9 AND 12 ONLY ALLOW TO ALL EMPLOYEES THEN REMAINING ALLOW ONLY A THIS MONTH DATE OF JOINING 
											if((int)$check_month_val <= 3){
												$salary_end_date = "$day_end-03-$cur_year";
											}else
											if((int)$check_month_val <= 6){
												$salary_end_date = "$day_end-06-$cur_year";
											}else
											if((int)$check_month_val <= 9){
												$salary_end_date = "$day_end-09-$cur_year";
											}else
											if((int)$check_month_val <= 12){
												$salary_end_date = "$day_end-12-$cur_year";
											}
										}else{
											$check_date = "";
										}
										
									}else
									if($manual_credit_type === 3){
										if($based_on_date <= $salary_start_date){ //Joined Before Fin Year
											$check_date         = $salary_start_date;
										}else //Joined Between Fin Year
										if(($based_on_date > $salary_start_date) && ($based_on_date < $salary_end_date)){
											$check_date         = $based_on_date;
										}
										//IF PROCESS MONTH 6 AND 12 ONLY ALLOW TO ALL EMPLOYEES REMAINING ALLOW A THIS MONTH DATE OF JOINING 
										$check_month_valid      = ($check_month_val-1)/6;
										if(is_int($check_month_valid) || (!array_key_exists($leave_name,$cr_month_type_arr[$emp_code][$cur_year]))){
											//PROCESS MONTH CHECK VALIDATION
											if((int)$check_month_val <= 6){
												$salary_end_date = "$day_end-06-$cur_year";
											}else
											if((int)$check_month_val <= 12){
												$salary_end_date = "$day_end-12-$cur_year";
											}
										}else{
											$check_date    = "";
										}
										
									}else
									if($manual_credit_type === 4){
										if($based_on_date <= $salary_start_date){ //Joined Before Fin Year
											$check_date    = $salary_start_date;
										}else //Joined Between Fin Year
										if(($based_on_date > $salary_start_date) && ($based_on_date < $salary_end_date)){
											$check_date    = $based_on_date;
										}
										//IF PROCESS MONTH 12 ONLY ALLOW TO ALL EMPLOYEES THEN REMAINING ALLOW ONLY A THIS MONTH DATE OF JOINING 
										$check_month_valid = ($check_month_val-1)/12;
										if(is_int($check_month_valid) || (!array_key_exists($leave_name,$cr_month_type_arr[$emp_code][$cur_year]))){
											//CHECK MOTH VALIDATION
											if((int)$check_month_val <= 12){
												$salary_end_date = "$day_end-12-$cur_year";							
											}
										}else{
											$check_date = "";
										}
										
									}
								}
								if($check_date){
									$interval           = $this->get_intervals($check_date,$salary_end_date);
									$month_count        = $interval->m+1;
									$cur_credit_count   = number_format($month_count*$credit_days,2);
									$total_credit_count = $prev_credit + $cur_credit_count;
									if($leave_opening_arr[$component_value][$emp_code]){
										if(($prev_credit !== number_format($total_credit_count, 2)) && ($eligible_days >= $total_credit_count)){
											$upd_qry .= $leave_name.'_credit = "'.$total_credit_count.'",';
										}
									}else{
										$ins_key .= $leave_name.'_credit,';
										$ins_val .= '"'.$total_credit_count.'",';
									}
									if(($prev_credit !== number_format($total_credit_count, 2)) && ($eligible_days >= $total_credit_count)){
										$insert_qry .= '("'.$fin_year_id.'","'.$cr_setting_id.'","'.$based_on_date.'","'.$components.'","'.$component_value.'","'.$emp_code.'","'.$leave_name.'","'.$cur_credit_count.'","'.$total_credit_count.'","'.$process_month.'","1","'.date("Y-m-d H:i:s").'"),';
									}
								}
							}
						}
					}
					//Update Query
					if($upd_qry){
						$credit_upd_qry       = 'UPDATE cw_leave_opening SET '.$upd_qry.'trans_updated_by = 1,trans_updated_date = "'.date("Y-m-d H:i:s").'" where employee_code = "'.$emp_code.'" and financial_setting_id = "'.$fin_year_id.'"';
						$credit_upd_info      = $this->db->query("CALL sp_a_run ('RUN','$credit_upd_qry')");
											
					}	
					if($ins_key){
						$credit_ins_qry       = 'INSERT INTO cw_leave_opening ('.$ins_key.'financial_setting_id,employee_code,component_value,trans_created_by,trans_created_date) VALUES('.$ins_val.'"'.$fin_year_id.'","'.$emp_code.'","'.$component_value.'","1","'.date("Y-m-d H:i:s").'")';	
						$credit_ins_info      = $this->db->query("CALL sp_a_run ('INSERT','$credit_ins_qry')");
						$insert_result        = $credit_ins_info->result();
						$credit_ins_info->next_result();
					}
				}
			}
			$insert_qry = rtrim($insert_qry,",");
			if($insert_qry){
				$credit_insert_qry       = 'INSERT into cw_leave_cr_upd_log (leave_financial_id,credit_setting_id,based_on_date,components,component_value,employee_code,leave_name,monthly_credit,total_credit,entry_month,trans_created_by,trans_created_date) VALUES '.$insert_qry.'';
				$credit_insert_info      = $this->db->query($credit_insert_qry);
				if($credit_insert_info){
					$this->update_schedule($process_month,$start_time,"1","Successfully Updated..");
					return true;
				}else{
					$this->update_schedule($process_month,$start_time,"0","No Data Available");
					return false;
				}
			}else{
				$this->update_schedule($process_month,$start_time,"0","No Data Available");
				return false;
			}
		}			
	}			
	public function update_schedule($process_month,$start_time,$status,$reason){
		$end_time = date("Y-m-d H:i:s");
		$cron_sch_qry       = 'INSERT INTO cw_credit_update_schedule (process_date,start_time,end_time,processed,remarks) VALUES("'.date("Y-m-d").'","'.$start_time.'","'.$end_time.'","'.$status.'","'.$reason.'")';
		$cron_sch_info        = $this->db->query("CALL sp_a_run ('INSERT','$cron_sch_qry')");
		$cron_sch_result      = $cron_sch_info->result();
		$cron_sch_info->next_result();
		if($cron_sch_result){
			$select_cr_upd_qry       = 'SELECT * FROM cw_leave_cr_upd_log WHERE entry_month = "'.$process_month.'"';
			$select_cr_upd_info      = $this->db->query("CALL sp_a_run ('SELECT','$select_cr_upd_qry')");
			$select_cr_upd_result    = $select_cr_upd_info->result_array();
			$select_cr_upd_info->next_result();
			if($select_cr_upd_result){
				echo json_encode(array('success' => TRUE, 'data' => $select_cr_upd_result, 'message' => "Successfully Updated to Credit Leave!!"));
			}else{
				echo json_encode(array('success' => FALSE, 'message' => "No Records Found?"));
			}
		}else{
			echo json_encode(array('success' => FALSE, 'message' => "No Records Found?"));
		}
	}
	public function get_intervals($from_date,$to_date){
		$d1 = new DateTime($from_date);
		$d2 = new DateTime($to_date);
		$interval = $d1->diff($d2);
		return $interval;		
	}
	public function date_diff($from_date,$to_date){
		$date1_ts = strtotime($from_date);
	    $date2_ts = strtotime($to_date);
	    $diff = $date2_ts - $date1_ts;
	    return round($diff / 86400);		
	}
	public function rounding_value($result, $round_mode){
		$final_result =0;
		if(($round_mode == 0.5) || ($round_mode == 1)){
			$final_result = round($result/$round_mode, 0)* $round_mode;
		}elseif($round_mode == '>1'){
			$final_result = ceil($result);
		}elseif($round_mode == '<1'){
			$final_result = floor($result);
		}elseif($round_mode == '<0.5'){
			$rslt   = explode('.', $result);
			$int_value  =  $rslt[0];
			$point_value =  $rslt[1];
			if((int)$point_value > 50){
				$final_result = $int_value.'.50';
			}else{
				$final_result = ceil($result);
			}
		}elseif($round_mode == '>0.5'){
			$rslt   = explode('.', $result);
			$int_value   =  $rslt[0];
			$point_value =  $rslt[1];
			if((int)$point_value >= 50){
				$final_result = round($result);
			}else{
				$final_result = $int_value.'.50';
			}
		}elseif($round_mode == '>95'){ 
			$rslt   = explode('.', $result); 
			$int_value  =  $rslt[0]; 
			$point_value =  $rslt[1]; 
			if($point_value > 0){ $point_value = substr($point_value, 0, 2); } 
			if(strlen($point_value) == 1){  $point_value = $point_value.'0';  } 
			if((int)$point_value > 95){ 
				$final_result = $int_value + 1; 
			}elseif((int)$point_value > 45 && (int)$point_value <= 95){
			   $final_result = $int_value + 0.5; 
			}else{ $final_result = round($result); }
		}elseif(((int)$round_mode == 5) || ((int)$round_mode == 10) || ((int)$round_mode == 50) || ((int)$round_mode == 100)){
			$final_result = (ceil($result)% $round_mode === 0) ? ceil($result) : round(($result+ $round_mode/2)/ $round_mode)*$round_mode;
		}elseif($round_mode == 0.1){
			$final_result = round($result, 2);
		}
		return $final_result;
	}

	public function check_posting_lock($process_month) {
		$posting_lock_qry    = 'SELECT COUNT(*) as count FROM cw_payroll_posting_lock WHERE trans_status = 1 and posting_month = "'.$process_month.'" and posting_lock = 1';
		$posting_lock_info   = $this->db->query("CALL sp_a_run ('SELECT','$posting_lock_qry')");
        $posting_lock_result = $posting_lock_info->result();
        $posting_lock_info->next_result();
        $lock_count = $posting_lock_result[0]->count;
        return $lock_count;
	}
	//DR CODE FOR UPDATE A LEAVE CREDIT VALUE IN LEAVE CRD UPD TABLE
	public function update_leave_credit(){
		$string_data        = json_decode($this->input->post('string_data'));
		$credit_name        = $this->input->post('credit_name');
		$prev_credit        = $this->input->post('prev_value');
		$month_new_credit   = $this->input->post('credit_value');
		$prime_cr_upd_id    = $string_data->prime_leave_cr_upd_log_id;
		$components         = $string_data->components;
		$component_value    = $string_data->component_value;
		$employee_code      = $string_data->employee_code;
		$leave_name         = $string_data->leave_name;
		$total_credit       = $string_data->total_credit;
		$fin_year_id        = $string_data->leave_financial_id;
		$process_month      = $string_data->entry_month;

		$check_lock_count   = $this->check_posting_lock($process_month);
        if((int)$check_lock_count > 0){
        	echo json_encode(array('success' => FALSE, 'message' => "Payroll Posting Locked for This Month!!"));
        	exit(0);
        }

		$final_tot_credit   = "";
		if($prev_credit < $month_new_credit){
			$month_credit      = $month_new_credit - $prev_credit;
			$final_tot_credit  = $month_credit + $total_credit;
		}else
		if($prev_credit > $month_new_credit){
			$month_credit      = $prev_credit - $month_new_credit;		
			$final_tot_credit  = $total_credit - $month_credit;
		}
		
		$final_tot_credit   = number_format($final_tot_credit, 2);
		$start_time         = date("Y-m-d H:i:s");
		$entry_date         = date("Y-m-d");	

		$credit_upd_qry     = 'UPDATE cw_leave_cr_upd_log SET monthly_credit = "'.$month_new_credit.'",total_credit = "'.$final_tot_credit.'",trans_updated_by = 1,trans_updated_date = "'.date("Y-m-d H:i:s").'" where prime_leave_cr_upd_log_id = "'.$prime_cr_upd_id.'" and employee_code = "'.$employee_code.'" and component_value = "'.$component_value.'"';
		$credit_upd_info    = $this->db->query("CALL sp_a_run ('RUN','$credit_upd_qry')");

		$opening_upd_qry    = 'UPDATE cw_leave_opening SET '.$leave_name.'_credit = "'.$final_tot_credit.'",trans_updated_by = 1,trans_updated_date = "'.date("Y-m-d H:i:s").'" where employee_code = "'.$employee_code.'" and financial_setting_id = "'.$fin_year_id.'"';

		$opening_upd_info   = $this->db->query("CALL sp_a_run ('RUN','$opening_upd_qry')");

		if($credit_upd_info){
			$return_rslt    = $this->update_schedule($process_month,$start_time,"1","Successfully Updated..");

		}else{
			$return_rslt    = $this->update_schedule($process_month,$start_time,"0","No Data Available");
		}
	}	
}
?>