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_cafsinfotech_in/application/controllers/Action_controller.php
<?php
/**********************************************************
	   Filename: Action Controller
	Description: Action Controller for all dynamic module controller.
		 Author: udhayakumar Anandhan
	 Created on: ?30 ?December ?2019
	Reviewed by:
	Reviewed on:
	Approved by:
	Approved on:
	-------------------------------------------------------
	Modification Details
	Changed by:
	Change Info:
	-------------------------------------------------------
***********************************************************/
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once("Secure_Controller.php");
ini_set("memory_limit","50000M");
ini_set("max_execution_time","60000");
ini_set('zlib.output_compression', 'Off'); // Disable output compression (important for binary files)
ini_set('default_charset', ''); // Set default content type to avoid character set issues
ini_set('implicit_flush', 'Off'); // Disable implicit flush
require('./application/libraries/dompdf/autoload.php');
require('./application/libraries/PHPSpreadsheet/autoload.php');
require './phpmailer/src/Exception.php';
require './phpmailer/src/PHPMailer.php';
require './phpmailer/src/SMTP.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Dompdf\Dompdf;
use DOMDocument;
use ZipArchive;
use phpmailer\PHPMailer\PHPMailer;
use phpmailer\PHPMailer\Exception;
#[\AllowDynamicProperties]
abstract class Action_controller extends Secure_Controller{
	public $control_name;
	public $logged_id;
	public $logged_role;
	public $logged_consultancy;
	public $logged_dept;
	public $prime_id;
	public $prime_table;
	public $leave_financial_info;
	public $financial_info;
	public $fanf_header_info;
	public $base_query            = "" ;
	public $quick_link            = array();
	public $table_head            = array();
	public $view_info             = array();
	public $form_info             = array();
	public $rowset_form_info      = array();
	public $role_condition;       
	public $select_query          = "";
	public $view_select           = "";
	public $all_pick              = array();
	public $master_pick           = array();
	public $components            = array();
	public $emp_pick_arr          = array();
	public $formula_result        = array();
	public $role_based_condition  = array();
	public $email_setting 		  = array();
	public $freeze_count 		  = array();
	public $password_encrypt 	  = array();
	public $category_month_day 	  = array();	
	public $general_setting_info  = array();
	public $company_info          = array();
	public $bind_info             = array();
	public $condition_info        = array();
	public $get_map_arr           = array();
	public $form_arr              = array();
	public $control_whr_cond;
	public $order_by_cond;
	
	private $db_conn_id;
	public $module_sts;
	public $module_id;
	public $condition_list       = array();
	public $session_list         = array();
	public $pick_list            = array();
	public $depen_auto_list      = array();
	public $form_condition_list  = array();
	public $row_view_list        = array();

	public $alias_control        = array("monthly_input"=>"employees","fandf_monthly_input"=>"employees","monthly_input_fms"=>"employees","pay_structure"=>"employees","process_payroll_fms"=>"employees","employee_onboard"=>"employees","employee_self_portal"=>"employees",);
	// ,"audit_trial"=>"employees"
	public $formula_allow        = array("employees"=>true,);
	
	public $mi_base              = array("monthly_input"=>"monthly_input","fandf_monthly_input"=>"monthly_input","monthly_input"=>"monthly_input","time_sheet"=>"time_sheet",);
	public $payroll_base         = array("process_payroll"=>"process_payroll","process_payroll"=>"process_payroll",);

	public $time_base            = array("request"=>"request","approval"=>"approval","direct_leave_entry"=>"direct_leave_entry",);

	public function __construct($module_id = NULL){
		parent::__construct($module_id);
		// ADDED BY ARN FOR FANDF IMPORT
		$this->load->model('Process_payroll_model');
		// ARN END
		$this->module_sts         = true;
		$this->db_conn_id         = $this->db->conn_id;
		$this->module_id          = $module_id; // UDY CHAG FOR $this->control_name
		$this->control_name       = strtolower($this->router->fetch_class());
		$this->logged_id          = $this->session->userdata('logged_id');
		$this->logged_role        = $this->session->userdata('logged_role');
		$this->logged_user_role   = $this->session->userdata('logged_user_role');
		$this->logged_emp_code    = $this->session->userdata('logged_emp_code');
		$this->logged_area_access = $this->session->userdata('logged_area_access');
		$this->logged_device_code = $this->session->userdata('logged_device_code');
		//IF MODULE IS PAST ATTENDANCE APPROVAL - TO - PAST ATTTENDANCE REQUEST
		if($this->control_name === "past_attendance_approval"){
			$this->control_name  = "past_attendance_request";
		}
		$this->prime_id           = "prime_".$this->control_name."_id";
		$this->prime_table        = $this->db->dbprefix($this->control_name);
		if($this->prime_table    === "cw_fandf_monthly_input"){
			$this->prime_table    = "cw_monthly_input";
		}
		$this->base_query         = "select @SELECT@ from $this->prime_table";
		$this->select_query       = "$this->prime_table.$this->prime_id,";
		$this->view_select        = "$this->prime_table.$this->prime_id,";

		/* UDY NEED TO GET CALIRITY */
		if($this->formula_allow[$module_id]){
			echo $this->create_formula_file();
			$this->load->model('Formula_model');	
			$this->load->model('Hr_methods_model');
		}
	}
	
	/******************** UDY _START **********************/	
	public function run_multi_qry($qry){
		/* 1. NEED TO VALID is array  */
		$sts       = false;
		$msg       = "no data processed";
		$data      = [];
		$final_qry = implode(';',array_column($qry,'qry') ?? []).";";
		// echo $final_qry;
		if(mysqli_multi_query($this->db_conn_id, $final_qry)){
			$sts = true;
			$msg = "Qry processed";
			$i   = 0;
			do{
				if($result = mysqli_store_result($this->db_conn_id)){
					while($row = mysqli_fetch_assoc($result)){
						$data[$i][] = $row;
					}
					mysqli_free_result($result);
				}else{
					$data[$i] = [];
				}
				$qry[$i]["rslt"] = json_decode(json_encode($data[$i]));
				$i++;
			}
			while(mysqli_more_results($this->db_conn_id) && mysqli_next_result($this->db_conn_id));
		}
		$final_rslt = [];
		if($sts){
			foreach ($qry as $key => $value) {
				$final_rslt[$value['return']] = $value['rslt'];
			}
		}
		return json_decode(json_encode(array("sts"=>$sts,"msg"=>$msg,"rslt"=>$final_rslt)));
    }
		
	public function page_info(){

		$this->control_whr_cond  = ""; 
		// UDY TEMP NNED TO REMOVE
		//EMPLOYEE MASTER BASED TABLE INPUTS		
		if($this->alias_control[$this->control_name]){
			$control_name = $this->alias_control[$this->control_name];
			//FOR MONTHLY INPUT 
			if($this->mi_base[$this->control_name]){
				$this->control_whr_cond  = ' and (earn_month_check = "1" OR deduction_month_check = "1")'; 
			}
			$emp_custom_join    = "";
			$emp_custom_whr     = "";
			
		}else{
			$control_name = $this->control_name;
		}	
		$order_by = ' ORDER BY input_for,field_sort asc';
		//FOR ONBOARD
		if($this->control_name === 'employee_onboard'){
			$this->control_whr_cond = ' and (cw_form_setting.onboard_order != "" and cw_form_setting.onboard_order != 0)';
			$order_by               = ' ORDER BY onboard_order asc';
		}else
		if($this->mi_base[$this->control_name]){//FOR MONTHLY INPUT
			$order_by               = ' ORDER BY monthly_input_sort asc';
		}		
		
		// UDY TEMP NEED TO REMOVE		
		$pro_qry     = [];
		$pro_qry[]   = array("return"=>"quicklink","qry"=>'select quicklink from cw_modules  where module_id = "'.$this->control_name.'"');
		//FORM INFO QUERY FOR EMPLOYEE SELF AND AUDIT TRIAL AND OTHERS BASED CONDITION
		//IF CONDTION ONLY FOR EMPLOYEE SELF PORTAL SEARCH
		if($this->control_name === "employee_self_portal"){
			$control_name      = "audit_trial";
		}
		// if($this->control_name !== "employee_self_portal"){ //and field_show = "1"
			$pro_qry[]   = array("return"=>"form_info","qry"=>'select * from cw_form_setting where prime_module_id = "'.$control_name.'" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",user_right_for)'.$this->control_whr_cond.$order_by);
		// }else{
		// 	$pro_qry[]   = array("return"=>"form_info","qry"=>'select cw_form_setting.* from cw_custom_design inner join cw_form_setting on cw_form_setting.label_name=cw_custom_design.label_name and cw_form_setting.prime_module_id=cw_custom_design.prime_module_id and cw_form_setting.input_for=cw_custom_design.input_for where cw_custom_design.prime_module_id="'.$control_name.'" and cw_custom_design.input_view in (1,2,3) and cw_form_setting.trans_status = "1" ORDER BY cw_form_setting.input_for,cw_form_setting.field_sort asc');
		// }
		$pro_qry[]   = array("return"=>"freeze_list","qry"=>'select left_freeze,right_freeze from cw_modules where module_id = "'.$this->control_name.'" and trans_status = "1"');
		$pro_qry[]   = array("return"=>"condition_list","qry"=>'select query_list_id,pick_where_condition from cw_pick_base_search where pick_module_id = "'.$this->control_name.'" AND FIND_IN_SET("'.$this->logged_user_role.'", pick_query_for) and trans_status = "1"');
		
		$pro_qry[]   = array("return"=>"session_list","qry"=>'select session_value from cw_session_value  where session_for = 1 and trans_status = "1" and session_value != "access_data"');
		//Company Information qry
		$pro_qry[]   = array("return"=>"company_info","qry"=>'select * from cw_company_information where cw_company_information.trans_status = 1');
		//financial year qry
		$pro_qry[]   = array("return"=>"financial_info","qry"=>'SELECT prime_financial_setting_id,start_date,end_date,old_rebate,old_m_relief,new_rebate,new_m_relief,old_sd,new_sd,landlord_pan_amt from cw_financial_setting where set_as_default_financial_year = 1 and trans_status = "1"');		
		
	
		if(count($pro_qry ?? []) > 0){
			$page_info_rslt         = $this->run_multi_qry($pro_qry);
			if(!$page_info_rslt->sts){				
				$this->module_sts   = false;
			}else{
				
				$condition_rslt     = [];
				$condition_list     = json_decode(json_encode($page_info_rslt->rslt->condition_list),true);
				if(count($condition_list ?? []) > 0){
					$condition_key  = array_column($condition_list, 'query_list_id');
					$condition_val  = array_column($condition_list, 'pick_where_condition');
					$condition_rslt = array_combine($condition_key ?? [], $condition_val);
				}

				$table_info         = [];
				$filter_info        = [];
				$pro_pick_list      = [];
				foreach($page_info_rslt->rslt->form_info as $key => $value){
					$field_type       = (int)$value->field_type;
					$table_show       = (int)$value->table_show;
					$search_show      = (int)$value->search_show;
					$input_view_type  = (int)$value->input_view_type;	
					//FOR MI AND MI FMS AND TIME SHEET
					if($this->mi_base[$this->control_name]){
						if($input_view_type !== 3){
							$table_info[$key]   = $value;
						}
						if(($field_type === 5) || ($field_type === 7) || ($field_type === 9)){
							$pro_pick_list[$key]  = $value;
						}
					}else{//FOE DEFAULT MODULE
						if($table_show === 1){
							if($input_view_type !== 3){
								$table_info[$key]   = $value;
							}
						}
						if($search_show === 1){
							$filter_info[$key]  = $value;
						}
						if(($search_show === 1) || ($table_show === 1)){
							if(($field_type === 5) || ($field_type === 7) || ($field_type === 9)){
								$pro_pick_list[$key]  = $value;
							}
						}
					}
				}
				array_multisort(array_column($table_info, 'table_sort'), SORT_ASC, $table_info);
				$this->quick_link           = $page_info_rslt->rslt->quicklink[0];
				$this->form_info            = $page_info_rslt->rslt->form_info;
				$this->freeze_list          = $page_info_rslt->rslt->freeze_list[0];
				$this->table_head           = $table_info;
				$this->fliter_list          = $filter_info;
				$this->condition_list       = $condition_rslt;
				$this->session_list         = $page_info_rslt->rslt->session_list;
				$this->company_info         = $page_info_rslt->rslt->company_info;
				$this->financial_info       = $page_info_rslt->rslt->financial_info;				
				if(count($pro_pick_list ?? []) > 0){
					$this->get_pick_list_qry($pro_pick_list);

					//ONLY FOR TIME SHEET
					if($this->mi_base[$this->control_name]){
						$this->get_import_pick_list_qry($pro_pick_list);
					}
				}

			}
		}
	}
	
	public function search_info(){
		$this->control_whr_cond  = ""; 
		// UDY TEMP NNED TO REMOVE
		//EMPLOYEE MASTER BASED TABLE INPUTS		
		if($this->alias_control[$this->control_name]){
			$control_name = $this->alias_control[$this->control_name];
			//FOR MI AND MI FMS AND TIME SHEET
			if($this->mi_base[$this->control_name]){
				$this->control_whr_cond  = ' and (earn_month_check = "1" OR deduction_month_check = "1")'; 
			}
		}else{
			$control_name = $this->control_name;
		}	
		$order_by = ' ORDER BY input_for,field_sort asc';
		//FOR ONBOARD
		if($this->control_name === 'employee_onboard'){
			$this->control_name     = 'employees';
			$this->control_whr_cond = ' and (cw_form_setting.onboard_order != "" and cw_form_setting.onboard_order != 0)';
			$order_by               = ' ORDER BY onboard_order asc';
		}else//FOR MI AND MI FMS AND TIME SHEET
		if($this->mi_base[$this->control_name]){
			$order_by               = ' ORDER BY monthly_input_sort asc';
		}		
		// UDY TEMP NNED TO REMOVE
		$pro_qry   = [];
		//FORM INFO QUERY FOR EMPLOYEE SELF AND AUDIT TRIAL AND OTHERS BASED CONDITION
		//IF CONDTION ONLY FOR EMPLOYEE SELF PORTAL SEARCH
		if($this->control_name === "employee_self_portal"){
			$control_name      = "audit_trial";
		}
		// $this->control_name !== "employee_self_portal" && 
		// if($this->control_name !== "audit_trial"){ //and field_show = "1"
			$pro_qry[]   = array("return"=>"form_info","qry"=>'select * from cw_form_setting where prime_module_id = "'.$control_name.'" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",user_right_for)'.$this->control_whr_cond.$order_by);
		// }else{
		// 	$pro_qry[]   = array("return"=>"form_info","qry"=>'select cw_form_setting.* from cw_custom_design inner join cw_form_setting on cw_form_setting.label_name=cw_custom_design.label_name and cw_form_setting.prime_module_id=cw_custom_design.prime_module_id and cw_form_setting.input_for=cw_custom_design.input_for where cw_custom_design.prime_module_id="'.$control_name.'" and cw_custom_design.input_view in (1,2,3) and cw_form_setting.trans_status = "1" ORDER BY cw_form_setting.input_for,cw_form_setting.field_sort asc');
		// }
		$controller_name_temp = strtolower($this->router->fetch_class());
		if($controller_name_temp === "past_attendance_approval"){
			$control_name = $controller_name_temp ;
		}else{
			$control_name = $this->control_name;
		}

		$pro_qry[] = array("return"=>"role_condition_list","qry"=>'select where_condition from cw_form_table_search where query_module_id = "'.$control_name.'" and FIND_IN_SET("'.$this->logged_user_role.'",query_for) and trans_status = "1"');

		$pro_qry[] = array("return"=>"session_list","qry"=>'select session_value from cw_session_value  where session_for = 1 and trans_status = "1" and session_value != "access_data"');
		//Company Information qry
		$pro_qry[] = array("return"=>"company_info","qry"=>'select * from cw_company_information where cw_company_information.trans_status = 1');
		//financial year qry
		$pro_qry[]   = array("return"=>"financial_info","qry"=>'SELECT prime_financial_setting_id,start_date,end_date,old_rebate,old_m_relief,new_rebate,new_m_relief,old_sd,new_sd,landlord_pan_amt from cw_financial_setting where set_as_default_financial_year = 1 and trans_status = "1"');
		
		if(count($pro_qry ?? []) > 0){
			$search_info_rslt = $this->run_multi_qry($pro_qry);
			if(!$search_info_rslt->sts){
				$this->module_sts = false;
			}else{
				$this->form_info      = $search_info_rslt->rslt->form_info;
				$this->session_list   = $search_info_rslt->rslt->session_list;
				//BASIC SEARCH TABLE ROLE BASE CONDITION START
				$role_condition_list  = $search_info_rslt->rslt->role_condition_list[0];
				$this->company_info   = $search_info_rslt->rslt->company_info;
				$this->financial_info = $search_info_rslt->rslt->financial_info;
				$where_condition      =  "";
				if($role_condition_list->where_condition){
					$where_condition           = $role_condition_list->where_condition;				
					$where_condition           = str_replace('^','"',$where_condition);
					foreach($this->session_list as $session_val){
						$session_value 	       = $session_val->session_value;
						$saved_session_val     = $this->session->userdata($session_value);
						$exist_val             = "@".$session_value."@";
						$where_condition       = str_replace($exist_val,$saved_session_val,$where_condition);
						$where_condition       = str_replace(',','","',$where_condition);
					}
				}
				$where_condition  = str_replace(',','","',$where_condition);
				$this->role_condition    = $where_condition;
				//BASIC SEARCH TABLE ROLE BASE CONDITION END

				$table_info        = [];
				$filter_info       = [];
				$pro_pick_list     = [];
				foreach($this->form_info as $key => $value){
					$table_show         = (int)$value->table_show;
					$search_show        = (int)$value->search_show;
					$field_type         = (int)$value->field_type;	
					$input_view_type    = (int)$value->input_view_type;	
					
					if($this->mi_base[$this->control_name]){
						if($input_view_type !== 3){
							$table_info[$key]   = $value;
						}
						if(($field_type === 5) || ($field_type === 7) || ($field_type === 9)){
							$pro_pick_list[$key]  = $value;
						}
					}else{
						if($table_show === 1){
							if($input_view_type !== 3){
								$table_info[$key]   = $value;
							}
							if(($field_type === 5) || ($field_type === 7) || ($field_type === 9)){
								$pro_pick_list[$key]  = $value;
							}
						}
						if($search_show === 1){
							$filter_info[$key]  = $value;
						}
					}
				}
				$this->table_head           = $table_info;
				$this->fliter_list          = $filter_info;
				
				$select_key              = array_column($this->table_head, "label_name");
				$this->select_query     .= implode(",",$select_key ?? []);
				//PICKLIST & AUTOCOMPLETE DATA
				if(!$this->mi_base[$this->control_name]){
					if(count($pro_pick_list ?? []) > 0){
						$this->get_pick_list_qry($pro_pick_list);
						//ONLY FOR TIME SHEET
						// if($this->mi_base[$this->control_name]){
						// 	$this->get_import_pick_list_qry($pro_pick_list);
						// }
					}
				}
			}	
		}
	}

	public function view_info($prime_id){
		// echo $this->control_name;
		if($this->alias_control[$this->control_name]){
			$control_name = $this->alias_control[$this->control_name];
		}else{
			$control_name = $this->control_name;
		}	
		// echo $control_name;
		$order_by                = ' ORDER BY input_for,field_sort asc';
		//UDS ONBOARD query
		if($this->control_name === 'employee_onboard'){
			$this->control_whr_cond = ' and (cw_form_setting.onboard_order != "" and cw_form_setting.onboard_order != 0)';
			$order_by = ' ORDER BY onboard_order asc';
		}	
		$pro_qry     = [];
		if($this->control_name === "audit_trial" || $this->control_name === "employee_log_report" || $this->control_name === "service_record"){
			$control_name   = "employees";
		}
		//FORM INFO QUERY FOR EMPLOYEE SELF AND AUDIT TRIAL AND OTHERS BASED CONDITION
		if($this->control_name !== "employee_self_portal" && $this->control_name !== "audit_trial"){
			// && $this->control_name !== "audit_trial"
			$pro_qry[]   = array("return"=>"form_info","qry"=>'select * from cw_form_setting where prime_module_id = "'.$control_name.'" and field_show = "1" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",user_right_for)'.$this->control_whr_cond.$order_by);
		}else{
			$pro_qry[]   = array("return"=>"form_info","qry"=>'select prime_custom_design_id,cw_form_setting.* from cw_custom_design inner join cw_form_setting on cw_form_setting.label_name=cw_custom_design.label_name and cw_form_setting.prime_module_id=cw_custom_design.prime_module_id and cw_form_setting.input_for=cw_custom_design.input_for where cw_custom_design.prime_module_id="'.$control_name.'" and cw_custom_design.input_view in (1,2,3) and cw_form_setting.trans_status = "1" ORDER BY cw_form_setting.input_for,cw_form_setting.field_sort asc');
		}
		//FORM VIEW INFO QUERY FOR EMPLOYEE SELF AND AUDIT TRIAL AND OTHERS BASED CONDITION
		// && $this->control_name !== "audit_trial"
		if($this->control_name !== "employee_self_portal"){
			$pro_qry[]   = array("return"=>"view_info","qry"=>'select DISTINCT cw_form_view_setting.* from cw_form_view_setting where prime_view_module_id = "'.$control_name.'" and cw_form_view_setting.form_view_show = "1" and cw_form_view_setting.trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",cw_form_view_setting.view_user_right) ORDER BY cw_form_view_setting.form_view_sort asc');
		}else{
			$pro_qry[]   = array("return"=>"view_info","qry"=>'select DISTINCT cw_form_view_setting.* from cw_custom_design inner join cw_form_view_setting on cw_form_view_setting.prime_form_view_id =cw_custom_design.input_for where cw_custom_design.prime_module_id = "'.$control_name.'" and prime_view_module_id = "'.$control_name.'" and cw_form_view_setting.form_view_show = "1" and cw_form_view_setting.trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",cw_form_view_setting.view_user_right) ORDER BY cw_form_view_setting.form_view_sort asc');
		}
		$pro_qry[]   = array("return"=>"formula_result","qry"=>'select * from cw_form_bind_input where input_cond_module_id = "'.$control_name.'" and trans_status = 1');

		//for read only option qry
		$pro_qry[]   = array("return"=>"role_based_condition","qry"=>'select * from cw_role_base_condition where  role_module_id = "'.$control_name.'" and find_in_set("'.$this->logged_user_role.'",role_condition_for) and trans_status = 1');

		$pro_qry[]   = array("return"=>"condition_list","qry"=>'select query_list_id,pick_where_condition from cw_pick_base_search where pick_module_id = "'.$this->control_name.'" AND FIND_IN_SET("'.$this->logged_user_role.'", pick_query_for) and trans_status = "1"');

		$pro_qry[]   = array("return"=>"session_list","qry"=>'select session_value from cw_session_value where session_for = 1 and trans_status = "1" and session_value != "access_data"');

		//DHR COMMAND FOR FORM CONDITION LIST (IT ADD FROM LAST) 
		if($this->control_name === "employee_self_portal"){
			$pro_qry[]   = array("return"=>"form_condition_list","qry"=>'select * from cw_form_condition_formula where cond_module_id = "employees" and trans_status = "1" and FIND_IN_SET("'.$this->logged_role.'",condition_for)');
		}else{
			$pro_qry[]   = array("return"=>"form_condition_list","qry"=>'select * from cw_form_condition_formula where cond_module_id = "'.$this->control_name.'" and trans_status = "1" and FIND_IN_SET("'.$this->logged_role.'",condition_for)');
		}
		//Get Company Info
		$pro_qry[]   = array("return"=>"company_info","qry"=>'select * from cw_company_information where cw_company_information.trans_status = 1');
		//DHR COMMAND FOR FORM CONDITION LIST (IT ADD FROM LAST) 	
		//financial year qry
		$pro_qry[]   = array("return"=>"financial_info","qry"=>'SELECT prime_financial_setting_id,start_date,end_date,old_rebate,old_m_relief,new_rebate,new_m_relief,old_sd,new_sd,landlord_pan_amt from cw_financial_setting where set_as_default_financial_year = 1 and trans_status = "1"');

		if(count($pro_qry ?? []) > 0){
			$view_info_rslt           = $this->run_multi_qry($pro_qry);

			if(!$view_info_rslt->sts){
				$this->module_sts     = false;
			}else{
				$condition_rslt       = [];
				$condition_list       = json_decode(json_encode($view_info_rslt->rslt->condition_list),true);
				if(count($condition_list ?? []) > 0){
					$condition_key    = array_column($condition_list, 'query_list_id');
					$condition_val    = array_column($condition_list, 'pick_where_condition');
					$condition_rslt   = array_combine($condition_key ?? [], $condition_val);
				}

				//FOR ROLE BASE CONDITIONS
				$role_based_condition = [];
				$role_based_list      = json_decode(json_encode($view_info_rslt->rslt->role_based_condition),true);					
				$role_based_arr       = explode(",",$role_based_list[0]['input_columns']);
				$pro_pick_list        = [];
				$depen_auto_pick_list = [];
				foreach($view_info_rslt->rslt->form_info as $key => $value){
					$field_type       = (int)$value->field_type;
					$field_show       = (int)$value->field_show;
					$depen_pick_list  = (int)$value->dependent_pick_list;		
					$label_id         = $value->label_name;
					$input_view_type  = (int)$value->input_view_type;
					if($field_show === 1){
						//Role Based Condition
						if(in_array($label_id,$role_based_arr)){
							if($field_type === 9){
								$role_based_condition[] = $label_id.'_hidden_'.$prime_form_id;
							}else
							if($field_type === 10){
								$role_based_condition[] = 'upload_'.$label_id;
							}else{
								$role_based_condition[] = $label_id;
							}
						}
						if($input_view_type !== 3){
							$this->view_select  .= "$this->prime_table.$label_id,";
						}
						//if($depen_pick_list === 2){
							if(($field_type === 5) || ($field_type === 7) || ($field_type === 9)){
								$pro_pick_list[$key]  = $value;
							}
						/*}else
						if($depen_pick_list === 1 && ($field_type === 5 || $field_type === 7)){
							$pro_pick_list[$key]  = $value;
						}else
						if($depen_pick_list === 1 && $field_type === 9){
							$depen_auto_pick_list[$key]    = $value;
							$pro_pick_list[$key]  = $value;
						}*/
					}
				}
				if(count($role_based_condition ?? []) > 0){
					$role_based_condition['readonly'] = implode(",",$role_based_condition ?? []);
				}	
				//VIEW INFO LIST
				$this->view_info            = $view_info_rslt->rslt->view_info;
				$this->form_info            = $view_info_rslt->rslt->form_info;
				$this->formula_result       = $view_info_rslt->rslt->formula_result;
				$this->role_based_condition = $role_based_condition;
				$this->condition_list       = $condition_rslt;
				$this->session_list         = $view_info_rslt->rslt->session_list;
				$this->company_info         = $view_info_rslt->rslt->company_info;
				$this->financial_info       = $view_info_rslt->rslt->financial_info;

				//DHR COMMAND FOR FORM CONDITION LIST (IT ADD FROM LAST) 
				$form_condition_rslt     = $view_info_rslt->rslt->form_condition_list;
				if(count($form_condition_rslt ?? []) > 0){
					$this->form_condition_list($form_condition_rslt);
				}
				//DHR COMMAND FOR FORM CONDITION LIST (IT ADD FROM LAST) 
				$this->view_select   = rtrim($this->view_select,',');
				// ONLY FOR EMPLOYEE
				if($this->control_name === "employees"){
					$this->view_select   = $this->view_select .',user_name,password';
				}	
				if(count($pro_pick_list ?? []) > 0){
					$this->get_pick_list_qry($pro_pick_list);
				}
				if(count($depen_auto_pick_list ?? []) > 0){
					if($prime_id){
						$this->get_depen_auto_list_qry($depen_auto_pick_list,$prime_id);
					}
				}
				//FOR ROW SET FORMAT START 
				$row_view_list  = array_filter($this->view_info ?? [], function ($value) {			
					return (json_decode(json_encode((int)$value->form_view_type === 3)));
				});

				if(count($row_view_list ?? []) > 0){
					$row_form_list    = array_reduce($this->form_info, function($result, $arr){
						if((int)$arr->input_view_type === 3 && (int)$arr->table_show === 1){
							$result[$arr->input_for][] = $arr;
						};
						return $result;
					}, array());
					//THIS FUNCTION WORK PENDING SO PLEASE DON'T REMOVE IT
					// $this->row_view_list     = $this->get_row_set_list($row_view_list,$row_form_list,$prime_id);
					//THIS FUNCTION WORK PENDING SO PLEASE DON'T REMOVE IT
				}
				//FOR ROW SET FORMAT END
			}	
		}
	}

	public function save_info(){
		if($this->alias_control[$this->control_name]){
			$control_name = $this->alias_control[$this->control_name];
		}else{
			$control_name = $this->control_name;
		}
		if($this->control_name === 'employee_onboard'){
			$control_name = 'employees';
		}
		$pro_qry     = [];
		//FORM INFO QUERY FOR EMPLOYEE SELF AND AUDIT TRIAL AND OTHERS BASED CONDITION
		// && $this->control_name !== "audit_trial"
		if($this->control_name !== "employee_self_portal"){
			$pro_qry[]   = array("return"=>"form_info","qry"=>'select * from cw_form_setting where prime_module_id = "'.$control_name.'" and field_show = "1" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",user_right_for)'.$this->control_whr_cond.$order_by);
		}else{
			$pro_qry[]   = array("return"=>"form_info","qry"=>'select prime_custom_design_id,cw_form_setting.* from cw_custom_design inner join cw_form_setting on cw_form_setting.label_name=cw_custom_design.label_name and cw_form_setting.prime_module_id=cw_custom_design.prime_module_id and cw_form_setting.input_for=cw_custom_design.input_for where cw_custom_design.prime_module_id="'.$control_name.'" and cw_custom_design.input_view in (1,2,3) and cw_form_setting.trans_status = "1" ORDER BY cw_form_setting.input_for,cw_form_setting.field_sort asc');
		}
		//Get Company Info
		$pro_qry[]   = array("return"=>"company_info","qry"=>'select * from cw_company_information where cw_company_information.trans_status = 1');
		$pro_qry[]   = array("return"=>"financial_info","qry"=>'SELECT prime_financial_setting_id,start_date,end_date,old_rebate,old_m_relief,new_rebate,new_m_relief,old_sd,new_sd,landlord_pan_amt from cw_financial_setting where set_as_default_financial_year = 1 and trans_status = "1"');
		$pro_qry[]   = array("return"=>"email_count_info","qry"=>'select count(*) as email_count from cw_modules where cw_modules.module_id = "'.$control_name.'" and cw_modules.email_setting = 1 and cw_modules.trans_status = 1');

		
		if(count($pro_qry ?? []) > 0){
			$search_info_rslt = $this->run_multi_qry($pro_qry);
			if(!$search_info_rslt->sts){
				$this->module_sts = false;
			}else{
				$this->form_info      = $search_info_rslt->rslt->form_info;
			}	
		}
		$this->company_info         = $search_info_rslt->rslt->company_info;
		$this->financial_info       = $search_info_rslt->rslt->financial_info;
		$this->email_count       	= $search_info_rslt->rslt->email_count_info[0]->email_count;
	}

	public function get_pick_list_qry($pro_pick_list){
		$pro_qry = [];
		foreach($pro_pick_list as $setting){
			$prime_form_id      = (int)$setting->prime_form_id;
			$prime_module_id    = $setting->prime_module_id;
			$input_view_type    = (int)$setting->input_view_type;
			$input_for          = (int)$setting->input_for;
			$field_type         = (int)$setting->field_type;
			$label_id           = $setting->label_name;
			$label_name         = ucwords($setting->view_name);
			$field_length       = $setting->field_length;
			$field_decimals     = $setting->field_decimals;
			$pick_list_type     = (int)$setting->pick_list_type;
			$pick_list          = $setting->pick_list;
			$pick_table         = $setting->pick_table;
			$auto_prime_id      = $setting->auto_prime_id;
			$auto_dispaly_value = $setting->auto_dispaly_value;
			$field_isdefault    = (int)$setting->field_isdefault;
			$file_type          = (int)$setting->file_type;
			$mandatory_field    = (int)$setting->mandatory_field;
			$unique_field       = (int)$setting->unique_field;
			$table_show         = (int)$setting->table_show;
			$search_show        = (int)$setting->search_show;
			$default_value      = (int)$setting->default_value;
			$pick_display       = $setting->pick_display_value;
			$pick_list_import   = (int)$setting->pick_list_import;
			
			if($default_value === 0){
				$default_value = "";
			}
			
			$pick_drop       = array();
			$pick_master     = array();
			$pick_key        = array();
			$pick_val        = array();
			$final_pick      = array();
			$where_condition = "";
			
			//ROLE BASE CONDITION BUILD
			if($this->condition_list[$prime_form_id]){
				$where_condition = $this->condition_list[$prime_form_id];				
				$where_condition = str_replace('^','"',$where_condition);
				foreach($this->session_list as $session_val){
					$session_value 	   = $session_val->session_value;
					$saved_session_val = $this->session->userdata($session_value);
					$exist_val = "@".$session_value."@";
					$where_condition  = str_replace($exist_val,$saved_session_val,$where_condition);
				}
				$where_condition  = str_replace(',','","',$where_condition);
			};

			if($field_isdefault === 1){	 // UDY NEED CHECK
				if(($field_type === 5) || ($field_type === 7)){
					if($pick_list_type === 1){
						$pick_list_val       = explode(",",$pick_list);
						$pick_list_val_1     = $pick_list_val[0];
						$pick_list_val_2     = $pick_list_val[1];
						$imp_pick_list_val_1 = $pick_list_val_1;
						$imp_pick_list_val_2 = $pick_list_val_2;
						if($pick_display){
							$pick_list = "$pick_list_val_1,CONCAT_WS(\" ~ \", $pick_display) as $pick_list_val_2";
							$pick_qry  = 'select '.$pick_list.' from '.$pick_table.' where trans_status = 1 '.$where_condition;
							$pick_qry  = rtrim($pick_qry," ");
							$pro_qry[] = array("return"=>$label_id,"qry"=>$pick_qry,"pro_info"=>array('prime_form_id' => $prime_form_id,'label_id' => $label_id,'label_name' => $label_name,'field_type' => $field_type,'pick_list_type' => $pick_list_type,'pick_list_val_1' => $pick_list_val_1,'pick_list_val_2' => $pick_list_val_2,'table_show' => $table_show,'search_show' => $search_show,'field_isdefault' => $field_isdefault,));
						}
					}else
					if($pick_list_type === 2){
						$pick_list_val_1 = $pick_table."_id";
						$pick_list_val_2 = $pick_table."_value";
						$pick_list_val_3 = $pick_table."_status";
						$pick_qry        = 'select '.$pick_list_val_1.','.$pick_list_val_2.' from '.$pick_table.' where '.$pick_list_val_3.' = 1'. $where_condition;
						$pick_qry        = rtrim($pick_qry," ");
						$pro_qry[]       = array("return"=>$label_id,"qry"=>$pick_qry,"pro_info"=>array('prime_form_id' => $prime_form_id,'label_id' => $label_id,'label_name' => $label_name,'field_type' => $field_type,'pick_list_type' => $pick_list_type,'pick_list_val_1' => $pick_list_val_1,'pick_list_val_2' => $pick_list_val_2,'table_show' => $table_show,'search_show' => $search_show,'field_isdefault' => $field_isdefault,));
					}
				}else
				if($field_type === 9){
					if($pick_display){
						$pick_display_val  = " ,CONCAT(".str_replace(",",'," ~ ",',$pick_display).") as auto_list_pick";
					}else{
						$pick_display_val  = "";
					}
					$pick_qry          = 'select '.$auto_prime_id.','.$auto_dispaly_value. $pick_display_val .' from '. $pick_table .' where trans_status = 1';
					$pick_qry          = rtrim($pick_qry," ");
					$pro_qry[]         = array("return"=>$label_id,"qry"=>$pick_qry,"pro_info"=>array('prime_form_id' => $prime_form_id,'label_id' => $label_id,'label_name' => $label_name,'field_type' => $field_type,'auto_prime_id' => $auto_prime_id,'auto_dispaly_value' => $auto_dispaly_value,'table_show' => $table_show,'search_show' => $search_show,'field_isdefault' => $field_isdefault,));
				}
			}
		}
		if(count($pro_qry ?? []) > 0){
			$pick_list_info = $this->run_multi_qry($pro_qry);
			if(!$pick_list_info->sts){
				$this->module_sts = false;
			}else{
				$pick_list_rslt = [];
				$pick_list_rslt = json_decode(json_encode($pick_list_info->rslt),true);

				foreach($pick_list_rslt as $pick_key=>$list_info){
					$is_exist_pro_qry = array_search($pick_key, array_column($pro_qry, 'return'));
					if($pro_qry[$is_exist_pro_qry]){
						//pro info array format
						$pro_info         = $pro_qry[$is_exist_pro_qry]["pro_info"];

						$prime_form_id    = $pro_info['prime_form_id'];
						$label_id         = $pro_info['label_id'];
						$label_name       = $pro_info['label_name'];
						$field_type       = (int)$pro_info['field_type'];
						$table_show       = (int)$pro_info['table_show'];
						$search_show      = (int)$pro_info['search_show'];
						$field_isdefault  = (int)$pro_info['field_isdefault'];

						if($field_type === 5 || $field_type === 7){
							$pick_list_type     = (int)$pro_info['pick_list_type'];
							$pick_list_val_1    = $pro_info['pick_list_val_1'];
							$pick_list_val_2    = $pro_info['pick_list_val_2'];
							// if($pick_list_type === 1){
								$pick_key   = array_column($list_info ?? [], $pick_list_val_1);
								$pick_val   = array_column($list_info ?? [], $pick_list_val_2);
								$final_pick = array_combine( $pick_key ?? [], $pick_val ?? []);
								if($final_pick){
									$final_pick = array("" => "---- $label_name ----") + $final_pick;
								}
							// }

						}else
						if($field_type === 9){
							$auto_prime_id      = $pro_info['auto_prime_id'];
							$auto_dispaly_value = $pro_info['auto_dispaly_value'];

							$pick_key   = array_column($list_info, $auto_prime_id);
							$pick_val   = array_column($list_info, 'auto_list_pick');
							if(count($pick_key ?? []) === count($pick_val ?? [])){
								$final_pick = array_combine( $pick_key ?? [], $pick_val ?? []);
							}
						}	
						$this->pick_list[$label_id] = array('label_id'=> $label_id, 'label_name'=> $label_name, 'field_isdefault'=> $field_isdefault, 'array_list'=> $final_pick, 'field_type'=> $field_type,'prime_form_id'=>$prime_form_id);
					}
				}
			}
		}
	}

	//FOR DEPENDENT AUTOCOMPLETE START (ONLY USING FOR FORM EDIT OPTION)
	public function get_depen_auto_list_qry($depen_auto_pick_list,$prime_id){
		$pro_qry = [];
		foreach($depen_auto_pick_list as $setting){
			$prime_form_id      = (int)$setting->prime_form_id;
			$prime_module_id    = $setting->prime_module_id;
			$input_view_type    = (int)$setting->input_view_type;
			$input_for          = (int)$setting->input_for;
			$field_type         = (int)$setting->field_type;
			$label_id           = $setting->label_name;
			$label_name         = ucwords($setting->view_name);
			$field_length       = $setting->field_length;
			$field_decimals     = $setting->field_decimals;
			$pick_list_type     = (int)$setting->pick_list_type;
			$pick_list          = $setting->pick_list;
			$pick_table         = $setting->pick_table;
			$auto_prime_id      = $setting->auto_prime_id;
			$auto_dispaly_value = $setting->auto_dispaly_value;
			$field_isdefault    = (int)$setting->field_isdefault;
			$file_type          = (int)$setting->file_type;
			$mandatory_field    = (int)$setting->mandatory_field;
			$unique_field       = (int)$setting->unique_field;
			$table_show         = (int)$setting->table_show;
			$search_show        = (int)$setting->search_show;
			$default_value      = (int)$setting->default_value;
			$pick_display       = $setting->pick_display_value;
			$pick_list_import   = (int)$setting->pick_list_import;

			if($default_value === 0){
				$default_value = "";
			}
			
			$pick_drop       = array();
			$pick_master     = array();
			$pick_key        = array();
			$pick_val        = array();
			$final_pick      = array();
			$where_condition = "";
			
			//ROLE BASE CONDITION BUILD
			if($this->condition_list[$prime_form_id]){
				$where_condition = $this->condition_list[$prime_form_id];				
				$where_condition = str_replace('^','"',$where_condition);
				foreach($this->session_list as $session_val){
					$session_value 	   = $session_val->session_value;
					$saved_session_val = $this->session->userdata($session_value);
					$exist_val = "@".$session_value."@";
					$where_condition  = str_replace($exist_val,$saved_session_val,$where_condition);
				}
				$where_condition  = str_replace(',','","',$where_condition);
			};

			if($field_isdefault === 1){	 // UDY NEED CHECK
				if($field_type === 9){
					$pick_display      = $pick_table.'.'.$pick_display;
					$pick_display      = str_replace(",",",$pick_table.",$pick_display);
					$pick_display_val  = "CONCAT(".str_replace(",",'," ~ ",',$pick_display).") as auto_list_pick";
					$pick_qry          = 'select '.$pick_table.'.'.$auto_prime_id.','.$pick_table.'.'.$auto_dispaly_value.','.$pick_display_val .' from '. $pick_table .' inner join '.$this->prime_table. ' on '.$this->prime_table.'.'.$label_id.' = '. $pick_table .'.'.$auto_prime_id.' where '.$pick_table.'.trans_status = 1 and '.$this->prime_table.'.trans_status = 1 and '.$this->prime_table.'.'.$this->prime_id.' = "'.$prime_id.'"';
					$pick_qry          = rtrim($pick_qry," ");

					$pro_qry[]         = array("return"=>$label_id,"qry"=>$pick_qry,"pro_info"=>array('prime_form_id' => $prime_form_id,'label_id' => $label_id,'label_name' => $label_name,'field_type' => $field_type,'auto_prime_id' => $auto_prime_id,'auto_dispaly_value' => $auto_dispaly_value,'table_show' => $table_show,'search_show' => $search_show,'field_isdefault' => $field_isdefault,));
				}
			}
		}

		if(count($pro_qry ?? []) > 0){
			$pick_list_info = $this->run_multi_qry($pro_qry);
			if(!$pick_list_info->sts){
				$this->module_sts = false;
			}else{
				$pick_list_rslt = [];
				$pick_list_rslt = json_decode(json_encode($pick_list_info->rslt),true);

				foreach($pick_list_rslt as $pick_key=>$list_info){
					$is_exist_pro_qry = array_search($pick_key, array_column($pro_qry, 'return'));
					if($pro_qry[$is_exist_pro_qry]){
						//pro info array format
						$pro_info         = $pro_qry[$is_exist_pro_qry]["pro_info"];

						$prime_form_id    = $pro_info['prime_form_id'];
						$label_id         = $pro_info['label_id'];
						$label_name       = $pro_info['label_name'];
						$field_type       = (int)$pro_info['field_type'];
						$table_show       = (int)$pro_info['table_show'];
						$search_show      = (int)$pro_info['search_show'];
						$field_isdefault  = (int)$pro_info['field_isdefault'];

						if($field_type === 9){
							$auto_prime_id      = $pro_info['auto_prime_id'];
							$auto_dispaly_value = $pro_info['auto_dispaly_value'];

							$pick_key           = array_column($list_info, $auto_prime_id);
							$pick_val           = array_column($list_info, 'auto_list_pick');
							$final_pick         = array_combine( $pick_key ?? [], $pick_val  ?? []);
						}						
						$this->depen_auto_list[$label_id] = $final_pick;
					}
				}
			}
		}
	}
	//FOR DEPENDENT AUTOCOMPLETE END (ONLY USING FOR FORM EDIT OPTION) 

	//FOR VIEW FORM CONDITION LIST(BY BUILD A JS CODE)
	public function form_condition_list($form_condition_rslt){
		$load_script = "";
		foreach($form_condition_rslt as $condition){			
			$prime_cond_id         = $condition->prime_cond_id;
			$cond_module_id        = $condition->cond_module_id;
			$condition_label_name  = strtolower(str_replace(" ","_",$condition->condition_label_name));
			$condition_type        = (int)$condition->condition_type;
			$condition_check_form  = explode(",",$condition->condition_check_form);
			$condition_bind_to     = explode(",",$condition->condition_bind_to);
			$on_bind_inputs        = "";
			$on_change_inputs      = "";
			$on_blur_inputs        = "";
			
			foreach($condition_bind_to as $label_name){
				// $this->control_name
				$cond_from_qry  = 'select field_type,label_name from cw_form_setting where prime_module_id = "'.$cond_module_id.'" and label_name in ("'.$label_name.'") ORDER BY input_for,field_sort asc';
				$cond_from_qry  = rtrim($cond_from_qry," ");

				$pro_qry[]      = array("return"=>$label_name,"qry"=>$cond_from_qry,"pro_info"=>array('label_name' => $label_name,'prime_cond_id' => $prime_cond_id,'cond_module_id' => $cond_module_id,'condition_label_name' => $condition_label_name,'condition_type' => $condition_type,'condition_check_form' => $condition_check_form,'condition_bind_to' => $condition_bind_to,));			

			}
		}
		if(count($pro_qry ?? []) > 0){
			$form_cond_info = $this->run_multi_qry($pro_qry);
			if(!$form_cond_info->sts){
				$this->module_sts = false;
			}else{
				$form_cond_rslt = [];
				$form_cond_rslt = json_decode(json_encode($form_cond_info->rslt),true);

				foreach($form_cond_rslt as $cond_key=>$cond_info){
					$is_exist_pro_qry = array_search($cond_key, array_column($pro_qry, 'return'));
					if($pro_qry[$is_exist_pro_qry]){
						//pro info array format
						$pro_info         = $pro_qry[$is_exist_pro_qry]["pro_info"];

						$field_type            = (int)$cond_info[0]['field_type'];
						//$label_name            = $pro_info['label_name'];
						$prime_cond_id         = $pro_info['prime_cond_id'];
						$cond_module_id        = $pro_info['cond_module_id'];
						$condition_label_name  = $pro_info['condition_label_name'];
						$condition_type        = (int)$pro_info['condition_type'];
						$condition_check_form  = $pro_info['condition_check_form'];
						$condition_bind_to     = $pro_info['condition_bind_to'];
						$label_name            = implode(",", $pro_info['condition_check_form'] ?? []);
						/*============ 
							NOTE:  AUTO COMPLETE BOX & FILE UPLOAD BOX ARE NOT INCLUDED IN ON LOAD SCRIPT
						============*/
						if(($field_type === 1) || ($field_type === 2) || ($field_type === 3) || ($field_type === 11) || ($field_type === 12)){
							$on_bind_inputs  .= "$label_name,";
						}else
						if(($field_type === 5) || ($field_type === 6) || ($field_type === 7) || ($field_type === 9)){
							$on_change_inputs  .= "$label_name,";
						}
						if($condition_type === 2){
							if(($field_type === 4) || ($field_type === 13)){
								$on_blur_inputs  .= "$label_name,";
							}
						}
					}
					$check_input = "";
					if($on_bind_inputs){
						$on_bind_input = rtrim($on_bind_inputs,',');
						$on_bind_input = str_replace(",",",#",$on_bind_input);
						$on_bind_input = "#".$on_bind_input;
						$check_input .= "$on_bind_input";
					}	
					
					if($on_change_inputs){
						$on_change_input = rtrim($on_change_inputs,',');
						$on_change_input = str_replace(",",",#",$on_change_input);
						$on_change_input = "#".$on_change_input;
						if($check_input){
							$check_input .= ",$on_change_input";
						}else{
							$check_input .= "$on_change_input";
						}

					}
					
					if($on_blur_inputs){
						$on_blur_input = rtrim($on_blur_inputs,',');
						$on_blur_input = str_replace(",",",#",$on_blur_input);
						$on_blur_input = "#".$on_blur_input;
						if($check_input){
							$check_input .= ",$on_blur_input";
						}else{
							$check_input .= "$on_blur_input";
						}
					}
					
					$send_for  = implode(",",$condition_check_form ?? []);
					$send_data = "prime_cond_id:$prime_cond_id,for_input:'$send_for',";
					foreach($condition_check_form as $check_form){
						$send_data .= "$check_form:$('#$check_form').val(),";
					}
					$send_data = "{".rtrim($send_data,',')."}";
					
					//BIND VALUE FROM DATABASE TABLE
					if($condition_type === 1){
						if($on_bind_input){
							$fill_input = "";
							foreach($condition_bind_to as $bind_to){
								$fill_val    = "ui.item.".$bind_to;
								$fill_input .= "$('#$bind_to').val($fill_val);\n";
							}
							$send_url     = site_url("$this->control_name/bind_autocomplete_suggest");
							$load_script .= "$('$on_bind_input').autocomplete({
												source: function(request, response) {
													$.getJSON('$send_url',{term:request.term, prime_cond_id:$prime_cond_id },response);
												},
												minChars:2,
												autoFocus: true,
												delay:10,
												appendTo: '.modal-content',
												select: function(e, ui) {
													$fill_input
													return false;
												}
											});\n";
						}
						if($on_change_input){
							$fill_input = "";
							foreach($condition_bind_to as $bind_to){
								$fill_val    = "rslt[0].".$bind_to;
								$fill_input .= "$('#$bind_to').val($fill_val);\n";
							}
							
							$send_url  = site_url("$this->control_name/bind_change_suggest");
							$load_script .= "$('$on_change_input').change(function(){
												var isValid = true;
												$('$on_change_input').each(function() {
												if ($(this).val() === '') {
													isValid = false;
													$(this).addClass('error');
												}else{
													$(this).removeClass('error');
												}
												});
												if(isValid){
													$.ajax({
														type: 'POST',
														url: '$send_url',
														data:$send_data,
														success: function(data) {
															var rslt = JSON.parse(data);
															$fill_input
														}
													});
												}
											});\n";
						}
					}else  //FOR WRITE CONDITIONS TYPE
					if($condition_type === 2){
						$fill_input = "";
						foreach($condition_bind_to as $bind_to){
							$fill_val    = "rslt.".$bind_to;
							$fill_input .= "$('#$bind_to').val($fill_val);\n $('#$bind_to').trigger('change');";
						}
						$send_url  = site_url("$this->control_name/calculation_suggest");
						$encKey    = $this->generateKey();
						//CODE FOR JS FUNCTION ADD
						$function_info = "function $condition_label_name(input_id){
											var isValid = true;
											// Encryption
											var encKey  = '$encKey';
											var encData = encrypt(encKey,$send_data);
											$('#'+input_id).each(function() {
												if ($(this).val() === '') {
													isValid = false;
													$(this).addClass('error');
												}else{
													$(this).removeClass('error');
												}
											});
											
											if(isValid){
												$.ajax({
													type: 'POST',
													url: '$send_url',
													data:encData,
													success: function(data) {
														var rslt = JSON.parse(data);
														$fill_input
													}
												});
											}
										}";
						if($on_bind_input){
							//$load_script .= "$('$on_bind_input').bind('keyup blur change', function(e) {
							$load_script .= "$('$on_bind_input').on('input change', function(e) { 
								$condition_label_name();
							});\n";
						}
						if($on_change_input){
							$load_script .= "$('$on_change_input').change(function(){
												var input_id = $(this).attr('id');
												$condition_label_name(input_id);
											});\n";
						}
						if($on_blur_input){
							$load_script .= "$('$on_blur_input').blur(function(){
												var input_id = $(this).attr('id');
												$condition_label_name(input_id);
											});\n";
						}
						$load_script .= "\n$function_info\n";
					}
					
				}
			}
		}
				
		$load_script .= "\nlet status      = document.getElementsByClassName('modal-title')[0];
            window.addEventListener('load', function(e){
                if (navigator.onLine) {
                    //status.innerHTML = 'User is online';
                    status.classList.add('success');
                    status.classList.add('success');
                } else {
                    status.innerHTML = 'Please Check Your Internet Connection...';
                    status.classList.remove('success');
                    status.classList.add('internet_modal_error');                    
                }
            }, false);            
            window.addEventListener('online', function(e){
               // status.innerHTML = 'User is back online';
                status.classList.remove('internet_modal_error');
                status.classList.add('success');
                location.reload();
            }, false);            
            window.addEventListener('offline', function(e){
                status.innerHTML = 'Please Check Your Internet Connection...';
                status.classList.remove('success');
                status.classList.add('internet_modal_error');
            }, false);\n
            $('.select2').on('select2:select', function(e){
				 $(this).focus();
			     e.preventDefault(); 
			});\n";
		if($load_script){
			$this->form_condition_list[] = $load_script;
		}		
	}

	public function get_row_set_list($row_view_list,$row_form_list,$prime_id){
		foreach($row_view_list as $view){
			$prime_form_view_id   = $view->prime_form_view_id;
			$prime_view_module_id = $view->prime_view_module_id;
			$form_view_label_name = $view->form_view_label_name;
			
			$div_id       	      = $form_view_label_name."_div_".$prime_form_view_id;
			$table_id             = $form_view_label_name."_tbl_".$prime_form_view_id;
			$table_name           = $this->control_name."_".$form_view_label_name;
			$row_prime_id         = "prime_".$table_name."_id";
			$table_name           =  $this->db->dbprefix($table_name);
			$table_prime_id       = "prime_".$this->control_name."_id";

			$table_head           = array();
			$thead_line           = "";
			$select_query         = "$table_name.$row_prime_id,$table_name.$table_prime_id,";
			$input_form_list      = $row_form_list[$prime_form_view_id];

			foreach($input_form_list as $form){
				$prime_form_id      = (int)$form->prime_form_id;
				$view_name          = $form->view_name;
				$label_name         = $form->label_name;
				$field_type         = (int)$form->field_type;
				$pick_list_type     = (int)$form->pick_list_type;
				$pick_list          = $form->pick_list;
				$pick_table         = $form->pick_table;
				$auto_prime_id      = $form->auto_prime_id;
				$auto_dispaly_value = $form->auto_dispaly_value;
				$date_type 	 		= $form->date_type;
				if((int)$field_type === 4){
					if((int)$date_type === 1){
						$select_query .= 'DATE_FORMAT('.$table_name.'.'.$label_name.', "%d-%m-%Y") as '.$label_name.' , ';
					}else{
						$select_query .= "$table_name.$label_name , ";
					}
				}else
				if((int)$field_type === 13){
					$select_query .= 'DATE_FORMAT('.$table_name.'.'.$label_name.', "%d-%m-%Y H:i:s") as '.$label_name.' , ';
				}else
				if(($field_type === 5) || ($field_type === 7)){
					if($pick_list_type === 1){
						$pick_list_val   = explode(",",$pick_list);
						$pick_list_val_1 = $pick_list_val[0];
						$pick_list_val_2 = $pick_list_val[1];
						
						$pick_query_as = $pick_table."_".$prime_form_id;
						$select_query .= "$pick_query_as.$pick_list_val_2 as $label_name , ";
						$pick_query .= " left join $pick_table as $pick_query_as on $pick_query_as.$pick_list_val_1 = $table_name.$label_name ";
					}else
					if($pick_list_type === 2){ 
						$pick_list_val_1 = $pick_table."_id";
						$pick_list_val_2 = $pick_table."_value";
						$pick_list_val_3 = $pick_table."_status";
						
						$pick_query_as = $pick_table."_".$prime_form_id;
						$select_query .= "$pick_query_as.$pick_list_val_2 as $label_name , ";
						$pick_query   .= " left join $pick_table as $pick_query_as on $pick_query_as.$pick_list_val_1 = $table_name.$label_name ";

					}
				}else
				if($field_type === 9){
					$pick_query_as = $pick_table."_".$prime_form_id;
					$select_query .= "$pick_query_as.$auto_dispaly_value as $label_name,";
					$pick_query .= " left join $pick_table as $pick_query_as on $pick_query_as.$auto_prime_id = $table_name.$label_name ";
				}else{
					$select_query .= "$table_name.$label_name , ";
				}
				$table_head[] = $label_name;
				$thead_line  .= "<th>$view_name</th>";
			}
			$thead            = "<tr>$thead_line<th>Option</th></tr>";
			$select_query     = rtrim($select_query,',');
			$select_query     = rtrim($select_query,' , ');
			$order_qry        = 'order by abs('.$table_name.'.'.$row_prime_id.') desc';

			$final_qry        = 'select '.$select_query.' from '.$table_name.' '.$pick_query.' where '.$table_name.'.'.$table_prime_id.' = "'.$prime_id.'" and '.$table_name.'.trans_status = "1" '.$order_qry;

			$pro_qry[$prime_form_view_id]        = array("return"=>$prime_form_view_id,"qry"=>$final_qry,"pro_info"=>array('table_head' => $table_head,'row_prime_id' => $row_prime_id,'form_view_label_name' => $form_view_label_name,'prime_form_view_id' => $prime_form_view_id,'table_id' => $table_id,'div_id' => $div_id,'thead' => $thead,));
			
		}
		
		if(count($pro_qry ?? []) > 0){
			$row_set_info = $this->run_multi_qry($pro_qry);
			if(!$row_set_info->sts){
				$this->module_sts = false;
			}else{
				$row_input_rslt  = [];
				$row_input_rslt  = json_decode(json_encode($row_set_info->rslt));

				$tr_line         = "";
				$row_view_array  = [];
				foreach($row_input_rslt as $key => $data){
					$td_line                = "";
					$pro_info               = $pro_qry[$key]["pro_info"];
					
					$table_head             = $pro_info['table_head'];
					$row_prime_id           = $pro_info['row_prime_id'];
					$form_view_label_name   = $pro_info['form_view_label_name'];
					$prime_form_view_id     = $pro_info['prime_form_view_id'];
					$table_id               = $pro_info['table_id'];
					$div_id                 = $pro_info['div_id'];
					$thead                  = $pro_info['thead'];
					if($prime_form_view_id){
						if(count((array)$data) > 0){
							foreach($table_head as $label){
								$datas_exp        = $data->$label;
								$rowset_form_info = $this->get_rowset_form_info();
								$field_type       = $rowset_form_info[$label]['field_type'];
								$value            = $data->$label;
								if((int)$field_type === 4 || (int)$field_type === 13){
									if($value === "00-00-0000" || $value === 'NULL' || $value === "00-00-0000 00:00:00"){
										$td_line .= "<td></td>";
									}else{
										$td_line .= "<td>$value</td>";
									}
								}else
								if((int)$field_type === 8){//textbox only
									$value = str_replace("~",'"',$value);
									$value = str_replace("`","'",$value);
									$value = str_replace("^","&",$value);
									$td_line .= "<td>$value</td>";
								}else
								if((int)$field_type === 10){
									if($datas_exp === "" || $datas_exp === NULL){
										$td_line .= "<td>No Preview Available</td>";
									}else{
										$td_line .= "<td><a href='$datas_exp' format.pdf='' target='_blank' style='cursor: pointer;''><i class='fa fa-download' style='color:red;' aria-hidden='true'></i></a></td>";
									}
								}else{
									$td_line .= "<td>$value</td>";
								}
							}
							
							$row_id   = $data->$row_prime_id;
							$tab_name = $this->control_name."_".$form_view_label_name;
							$illustration_btn = "";
							if($form_view_label_name === "eligibility_information"){
								$illustration_btn   = "<a class='btn btn-edit btn-xs row_btn' onclick = add_illustration('$row_id','$tab_name','$prime_form_view_id');>Illustration</a>";
							}
							$edit_btn   = "<a class='btn btn-edit btn-xs row_btn' onclick = row_set_edit('$row_id','$tab_name','$prime_form_view_id','$prime_id');>Edit</a>";
							$remove_btn = "<a class='btn btn-danger btn-xs row_btn' onclick = row_set_remove('$row_id','$tab_name','$prime_form_view_id','$prime_id');>Delete</a>";
							$tr_line = "<tr>$td_line<td>$illustration_btn $edit_btn $remove_btn</td></tr>";
						}
						$row_set_view    = "<table id='$table_id' class='table table-bordered' style='background-color: #FFFFFF; box-shadow: none;'>
										<thead>$thead</thead>
										<tbody>$tr_line</tbody>
									</table>";
						$row_view_array[$prime_form_view_id]  = array('div_id' => $div_id, 'table_id' => $table_id,'row_set_view'=>$row_set_view);
					}
				}
				return $row_view_array;
			}
		}
	}
	/******************** UDY END *************************/
	/******************** DR FOR TIME OFFICE REQUIRED FUNCTION 1DEC22 START ************************/
	// Get Default Leave Financial Year
	public function get_leave_financial_details(){
		$fin_query = 'SELECT prime_leave_financial_year_id,starting_date,ending_date from cw_leave_financial_year where set_as_default_financial_year = 1 and trans_status = "1"';
		$fin_data   = $this->db->query("CALL sp_a_run ('SELECT','$fin_query')");
		$fin_result = $fin_data->result();
		$fin_data->next_result();
		return $fin_result;				
	}

	//GET A CATEGORY WISE MONTH DAY GET
	public function category_month_day(){
		$cat_month_day_qry        = 'SELECT * from cw_month_day where trans_status = "1"';
		$cat_month_day_data       = $this->db->query("CALL sp_a_run ('SELECT','$cat_month_day_qry')");
		$cat_month_day_rslt       = $cat_month_day_data->result_array();
		$cat_month_day_data->next_result();

		$cat_month_day_arr        = array_reduce($cat_month_day_rslt, function ($result, $arr) {		
		    $result[$arr['category']] = $arr;
		    return $result;
		}, array());
		return $cat_month_day_arr;				
	}

	// General setting query function
	public function general_setting_info(){
		$general_set_qry            = 'select * from cw_general_setting where trans_status = 1';
		$general_set_info           = $this->db->query("CALL sp_a_run ('SELECT','$general_set_qry')");
		$general_set_rslt           = $general_set_info->result();
		$general_set_info->next_result();
		return $general_set_rslt;
	}

	//Employee master picklist column get function
	public function time_setting_components(){
		$get_components        = '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')");
		$get_components_result = $get_components_info->result();
		$get_components_info->next_result();
		$components[""]        = "---- Select Component ----";
		foreach($get_components_result as $component){
			$prime_form_id     = $component->prime_form_id;
			$components_name   = strtoupper($component->view_name);
			$components[$this->xss_clean($prime_form_id)] = $this->xss_clean($components_name);		
		}
		return $components;
	}
	//FUNCTION FOR GET A EMPLOYEE PICKLIST LABEL NAMES FROM FORM SETTING TABLE
	public function get_emp_data(){
		$employee_code         = $this->session->userdata('logged_emp_code');	
		//QUERY FOR GET A EMPLOYEE PICKLIST LABEL NAMES FROM FORM SETTING TABLE
		$get_components        = 'select GROUP_CONCAT(label_name) as label_name from `cw_form_setting` where prime_module_id = "employees" and input_view_type in (1,2) and field_type = 5 ORDER BY label_name';
		$get_components_info   = $this->db->query("CALL sp_a_run ('SELECT','$get_components')");
		$get_components_result = $get_components_info->result();
		$get_components_info->next_result();
		$label_names           = $get_components_result[0]->label_name;	
		if((int)$this->logged_user_role === 1 || (int)$this->logged_user_role === 2){
			$qry = "";
		}else{
			$qry = 'employee_code = "'. $employee_code .'" and';
		}
		$emp_pick_query  = 'SELECT role as category,'.$label_names.',employee_code from cw_employees WHERE '.$qry.'  trans_status = 1';
		$emp_pick_info   = $this->db->query("CALL sp_a_run ('SELECT','$emp_pick_query')");
		$emp_pick_rlst   = $emp_pick_info->result_array();
		$emp_pick_info->next_result();

		$emp_pick_arr    = array_reduce($emp_pick_rlst, function($result, $arr){			
	    	$result[$arr['employee_code']] = $arr;
	    	return $result;
		}, array());
		return $emp_pick_arr;
	}
	//BSK Get Active Salary date for Timeoffice
	public function get_tos_active_salary_date(){
		//GET DEFAULT FINANCIAL YEAR
		$financial_info         = $this->get_leave_financial_details();
		$prime_financial_id     = $financial_info[0]->prime_leave_financial_year_id;	
		$starting_date          = date('Y-m-d',strtotime($financial_info[0]->starting_date));	
		$ending_date            = date('Y-m-d',strtotime($financial_info[0]->ending_date));	
		
		//GET Salary Last Processed Month Category wise
		$max_transaction_query  = 'SELECT role as category,date_format(MAX(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y")) , "%m-%Y") AS process_month from cw_transactions group by cw_transactions.role';			
		$max_transaction_info   = $this->db->query("CALL sp_a_run ('SELECT','$max_transaction_query')");
		$max_transaction_result = $max_transaction_info->result_array();
		$max_transaction_info->next_result();        

		$cat_rslt_arr = array_reduce($max_transaction_result, function($result, $arr){			
			$result[$arr['category']] = $arr['process_month'];
			return $result;
		}, array());

		$month_day_query  = 'SELECT category,day_conditions,day_start,day_end,day_count from cw_month_day where cw_month_day.trans_status = 1';			
		$month_day_info   = $this->db->query("CALL sp_a_run ('SELECT','$month_day_query')");
		$month_day_result = $month_day_info->result_array();
		$month_day_info->next_result();

		$final_arr = array();
		if($month_day_result){
			foreach ($month_day_result as $key => $month_day_res) {
				$day_conditions = $month_day_res['day_conditions'];
				$category       = $month_day_res['category'];
				$day_start      = $month_day_res['day_start'];
				$day_end        = $month_day_res['day_end'];
				$day_count      = $month_day_res['day_count'];
				$process_month  = $cat_rslt_arr[$category];
				if($process_month){
					$date = new DateTime("01-$process_month 00:00:00");
					$date->modify('+1 month');
					$process_month = $date->format("m-Y");	
					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';
						$day_end   = $day_count;
						$date = new DateTime("01-$process_month 00:00:00");
						$salary_start_date = $date->format("Y-m-$sal_start");	
						if((int)$day_conditions === 2){
							$salary_end_date   = date("Y-m-t",strtotime("01-".$process_month));
						}else{
							$salary_end_date   = date("Y-m-d",strtotime($day_end."-".$process_month));
						}
					}
					$final_arr[$category] = array('salary_start_date'=>$salary_start_date,'salary_end_date'=>$salary_end_date,'year_end_date'=>$ending_date);
				}else{
					$final_arr[$category] = array('salary_start_date'=>$starting_date,'salary_end_date'=>$ending_date,'year_end_date'=>$ending_date);
				}
			}
		}
		return $final_arr;
	}
	/******************** DR FOR TIME OFFICE REQUIRED FUNCTION 1DEC22 END ************************/

	//PROVIDE BASE DATA FOR MODULE
	public function collect_base_info(){
		$this->control_name      = strtolower($this->router->fetch_class());
		//IF MODULE IS PAST ATTENDANCE APPROVAL - TO - PAST ATTTENDANCE REQUEST
		if($this->control_name === "past_attendance_approval"){
			$this->control_name  = "past_attendance_request";
		}
		$this->logged_id         = $this->session->userdata('logged_id');
		$this->logged_role       = $this->session->userdata('logged_role');
		$this->logged_user_role  = $this->session->userdata('logged_user_role');
		$this->logged_emp_code   = $this->session->userdata('logged_emp_code');
		$this->prime_id          = "prime_".$this->control_name."_id";
		$this->prime_table       = $this->db->dbprefix($this->control_name);
		$this->base_query        = "select @SELECT@ from $this->prime_table";
		$this->select_query      = "$this->prime_table.$this->prime_id,";
		if($this->control_name === "employee_log_report"){
			$this->control_name  = "employees";
		}
		$this->get_quick_link();
		$this->get_table_head();		
		$this->get_view_info();
		$this->get_form_info();
		$this->get_leave_financial_details();		
		// $this->get_financial_year();
		$this->get_role_condition();
		$this->get_query_and_drop();
		$this->get_condition();
		$this->get_financial_year();
		$this->coloring_label();
		$this->role_based_condition();
		$this->get_freeze_count();
		$this->get_password_encrypt();
		$this->get_email_setting();
		$this->get_table_info();
		$this->get_fandf_header_info();
		$this->category_month_day();
		$this->general_setting_info();
		$this->company_info();
		$this->get_bind_info();
		$this->column_mapping();
		$this->get_tos_active_salary_date();
		if($this->control_name === 'request' || $this->control_name === 'direct_leave_entry' || $this->control_name === 'approval'){
			$this->get_emp_data();
		}
	}
	
	/* ==============================================================*/
	/* =================== BASE FUNCTIONS - START ===================*/
	/* ==============================================================*/
	public function get_bind_info(){
		$input_query  = 'select * from cw_form_bind_input where trans_status = 1';
		$input_data   = $this->db->query("CALL sp_a_run ('SELECT','$input_query')");
		$input_result = $input_data->result_array();
		$input_data->next_result();
		$input_result    = array_reduce($input_result, function($result, $arr){			
	    	$result[$arr['input_cond_id']][] = $arr;
	    	return $result;
		}, array());

		//Get form condition formula
		$cond_query  = 'select * from cw_form_condition_formula where trans_status = 1';
		$cond_data   = $this->db->query("CALL sp_a_run ('SELECT','$cond_query')");
		$cond_result = $cond_data->result_array();
		$cond_data->next_result();

		$cond_result    = array_reduce($cond_result, function($result, $arr){			
	    	$result[$arr['prime_cond_id']][] = $arr;
	    	return $result;
		}, array());
		//prime_cond_id = "'.$prime_cond_id.'" and

		$this->bind_info = $input_result;		
		$this->condition_info = $cond_result;		
	}

	// PROVIDE QUICK LINK LIST VIEW
	public function get_quick_link(){
		$link_query       = 'select quicklink from cw_modules  where module_id = "'.$this->control_name.'"';
		$link_info        = $this->db->query("CALL sp_a_run ('SELECT','$link_query')");
		$link_result      = $link_info->result();
		$link_info->next_result();
		$this->quick_link = $link_result[0];
	}
	
	// PROVIDE TABLE VIEW
	public function get_table_head(){
		$table_query = 'select label_name,view_name,field_type,date_type from cw_form_setting  where prime_module_id = "'.$this->control_name.'" and input_view_type IN (1,2) and table_show = "1" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",user_right_for) ORDER BY table_sort asc';
		$table_info = $this->db->query("CALL sp_a_run ('SELECT','$table_query')");
		$result   = $table_info->result();
		$table_info->next_result();
		$this->table_head    = $result;
		$select_key          = array_column($result, "label_name");
		$this->select_query .= implode(",",$select_key ?? []);
	}
	//F and F Header Details
	// PROVIDE MONTHLY INPUT TABLE VIEW
	public function get_fandf_header_info(){
		$fanf_header_qry = 'select label_name,view_name,field_type from cw_form_setting  where prime_module_id = "employees" ORDER BY prime_form_id';
		$fanf_header_info = $this->db->query("CALL sp_a_run ('SELECT','$fanf_header_qry')");
		$fanf_header_result   = $fanf_header_info->result();
		$fanf_header_info->next_result();
		$this->fanf_header_info = $fanf_header_result;
	}
	// PROVIDE TABLE VIEW
	public function get_freeze_count(){
		$freeze_table_query = 'select left_freeze,right_freeze from cw_modules  where module_id = "'.$this->control_name.'" and trans_status = "1"';
		$freeze_table_info = $this->db->query("CALL sp_a_run ('SELECT','$freeze_table_query')");
		$freeze_result   = $freeze_table_info->result();
		$freeze_table_info->next_result();
		$this->freeze_list 	  = $freeze_result;
	}
	//PAssword Encrty
	public function get_password_encrypt(){
		$emp_data_qry = 'select employee_code,emp_name,date_of_birth,date_of_joining from cw_employees where trans_status = 1';
		$emp_data     = $this->db->query("CALL sp_a_run ('SELECT','$emp_data_qry')");
		$empresult = $emp_data->result_array();
		$emp_data->next_result();
		$this->emp_data_result = array_reduce($empresult, function ($result, $arr) {		
			    $result[$arr['employee_code']] = $arr;
			    return $result;
			}, array());
	}
	
	// PROVIDE MODLE VIEWS
	public function get_view_info(){
		$view_query = 'select * from cw_form_view_setting  where prime_view_module_id = "'.$this->control_name.'" and form_view_show = "1" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",view_user_right) ORDER BY form_view_sort asc';
		$view_data   = $this->db->query("CALL sp_a_run ('SELECT','$view_query')");
		$view_result = $view_data->result();
		$view_data->next_result();
		$this->view_info = $view_result;
	}
	
	// PROVIDE MODLE FORM INPUT VIEWS
	public function get_form_info(){
		if($this->control_name === 'monthly_input' || $this->control_name === 'fandf_monthly_input'){
			$control_name = 'employees';
		}else{
			$control_name = $this->control_name;
		}
		$from_query = 'select * from cw_form_setting  where prime_module_id = "'.$control_name.'" and field_show = "1" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",user_right_for) ORDER BY input_for,field_sort asc';
		$form_data   = $this->db->query("CALL sp_a_run ('SELECT','$from_query')");
		$form_result = $form_data->result();
		$form_data->next_result();
		$this->form_info = $form_result;
	}
	public function get_rowset_form_info(){
		$table_query = 'select label_name,view_name,field_type from cw_form_setting  where prime_module_id = "'.$this->control_name.'" and input_view_type IN (3) and table_show = "1" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",user_right_for) ORDER BY table_sort asc';
		$table_info = $this->db->query("CALL sp_a_run ('SELECT','$table_query')");
		$result   = $table_info->result_array();
		$table_info->next_result();
		$result = array_map(function($v){
		    return [$v['label_name'] => $v];
		}, $result);
		$result = call_user_func_array('array_merge', $result);
		$this->rowset_form_info    = $result;		
		return $result;
	}
	
	// PROVIDE MODLE TABLE ROLE BASED SEARCH
	public function get_role_condition(){
		$table_search_query = 'select where_condition from cw_form_table_search where query_module_id = "'.$this->control_name.'" and FIND_IN_SET("'.$this->logged_user_role.'",query_for) and trans_status = "1"';
		$table_search_data   = $this->db->query("CALL sp_a_run ('SELECT','$table_search_query')");
		$table_search_result = $table_search_data->result();
		$table_search_data->next_result();
		if($table_search_result){
			$where_condition  = str_replace('^','"',$table_search_result[0]->where_condition);
			$session_query  = 'select session_value from cw_session_value  where session_for = 1 and trans_status = "1"';
			$session_data   = $this->db->query("CALL sp_a_run ('SELECT','$session_query')");
			$session_result = $session_data->result();
			$session_data->next_result();
			foreach($session_result as $rslt){
				$session_value 	   = $rslt->session_value;
				if($session_value !== "access_data"){
					$saved_session_val = $this->session->userdata($session_value);
					$exist_val = "@".$session_value."@";
					$where_condition  = str_replace($exist_val,$saved_session_val,$where_condition);
					}
			}
			$where_condition  = str_replace(',','","',$where_condition);
			$this->role_condition = $where_condition;
		}
	}
	// PROVIDE ROLE BASED PICK LIST /*UDY-13-02-2020*/
	public function get_role_based_picklist($query_list_id,$module_id){		
		$logged_user_role = str_replace(',', '|', $this->logged_user_role);
		$pick_query = 'select pick_where_condition from cw_pick_base_search  where pick_module_id = "'.$module_id.'" and query_list_id = "'.$query_list_id.'" and pick_query_for REGEXP "(^|,)('.$logged_user_role.')(,|$)" and trans_status = "1"';
		$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
		$pick_result = $pick_data->result();
		$pick_data->next_result();
		$where_condition = "";
		if($pick_result){
			$where_condition  = str_replace('^','"',$pick_result[0]->pick_where_condition);
			$session_query  = 'select session_value from cw_session_value  where session_for = 1 and trans_status = "1"';
			$session_data   = $this->db->query("CALL sp_a_run ('SELECT','$session_query')");
			$session_result = $session_data->result();
			$session_data->next_result();
			foreach($session_result as $rslt){
				$session_value 	   = $rslt->session_value;
				if($session_value !== "access_data"){
					$saved_session_val = $this->session->userdata($session_value);
					$exist_val = "@".$session_value."@";
					$where_condition  = str_replace($exist_val,$saved_session_val,$where_condition);
				}
			}
		}
		$where_condition  = str_replace(',','","',$where_condition);
		return $where_condition;
	}
	// Get Default Financial Year
	public function get_financial_year(){
		$fin_query = 'SELECT prime_financial_setting_id,start_date,end_date,old_rebate,old_m_relief,new_rebate,new_m_relief,old_sd,new_sd,tan_no,pan_or_gnr_no from cw_financial_setting where set_as_default_financial_year = 1 and trans_status = "1"';
		$fin_data   = $this->db->query("CALL sp_a_run ('SELECT','$fin_query')");
		$fin_result = $fin_data->result();
		$fin_data->next_result();
		$this->financial_info = $fin_result;
		return $fin_result;
	}
	//PROVIDE SEARCH AND VIEW SELECT QUERY, DROPDOWN VALUES AND SEARCH FLITERS
	public function get_query_and_drop(){
		$this->view_select  = "$this->prime_table.$this->prime_id,";
		foreach($this->form_info as $setting){
			$prime_form_id      = (int)$setting->prime_form_id;
			$prime_module_id    = $setting->prime_module_id;
			$input_view_type    = (int)$setting->input_view_type;
			$input_for          = (int)$setting->input_for;
			$field_type         = (int)$setting->field_type;
			$label_id           = $setting->label_name;
			$label_name         = ucwords($setting->view_name);
			$field_length       = $setting->field_length;
			$field_decimals     = $setting->field_decimals;
			$pick_list_type     = (int)$setting->pick_list_type;
			$pick_list          = $setting->pick_list;
			$pick_table         = $setting->pick_table;
			$auto_prime_id      = $setting->auto_prime_id;
			$auto_dispaly_value = $setting->auto_dispaly_value;
			$field_isdefault    = (int)$setting->field_isdefault;
			$file_type          = (int)$setting->file_type;
			$mandatory_field    = (int)$setting->mandatory_field;
			$unique_field       = (int)$setting->unique_field;
			$search_show        = (int)$setting->search_show;
			$default_value      = (int)$setting->default_value;
			$pick_display       = $setting->pick_display_value;
			if($default_value === 0){
				$default_value = "";
			}
			$pick_drop   = array();
			$pick_master = array();
			$pick_key    = array();
			$pick_val    = array();
			$final_pick  = array();
			if($field_isdefault === 1){				
				if(($field_type === 5) || ($field_type === 7)){
					$where_condition = $this->get_role_based_picklist($prime_form_id,$prime_module_id);
					if($pick_list_type === 1){
						$pick_list_val   = explode(",",$pick_list);
						$pick_list_val_1 = $pick_list_val[0];
						$pick_list_val_2 = $pick_list_val[1];
						if($pick_display){
							$pick_list = "$pick_list_val_1,CONCAT_WS(\" - \", $pick_display) as $pick_list_val_2";
						}
						if($label_name === 'loan_type' && $prime_module_id === 'loan'){
							$where_condition = ' and loan_check = 1';
						}
						if($pick_table === "cw_category"){ //and prime_category_id != 1
							$pick_query = "select $pick_list from $pick_table where trans_status = 1 $where_condition";
						}else
						if($pick_table === "cw_print_info" && $label_id === "design_template" || $label_id === "template"){
							$pick_query = "select $pick_list from $pick_table where trans_status = 1 and print_info_module_id = \"$this->control_name\" $where_condition";
						}else{
							$pick_query = "select $pick_list from $pick_table where trans_status = 1 $where_condition";
						}
						$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 ?? []);
						}
						$final_pick = array("" => "---- $label_name ----") + $final_pick;
						$this->master_pick[$label_id]   = $final_pick;
						 //array_unshift($final_pick,"---- $label_name ----");
						$this->all_pick[$prime_form_id] = $final_pick;
	  					//THIS IS GET A EMPLOYEE ALL PICKLISTS
						$get_components = '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')");
						$get_components_result = $get_components_info->result();
						$get_components_info->next_result();
						$components[""]        = "---- Select Component ----";
						foreach($get_components_result as $component){
							$prime_form_id     = $component->prime_form_id;
							$components_name   = strtoupper($component->view_name);
							$this->components[$this->xss_clean($prime_form_id)] = $this->xss_clean($components_name);	
							// $this->emp_label_arr[$this->xss_clean($prime_form_id)] = $this->xss_clean($component->label_name);	
						}
					}else
					if($pick_list_type === 2){
						$pick_list_val_1 = $pick_table."_id";
						$pick_list_val_2 = $pick_table."_value";
						$pick_list_val_3 = $pick_table."_status";
						
						$pick_query = "select $pick_list_val_1,$pick_list_val_2 from $pick_table where $pick_list_val_3 = 1 $where_condition";
						$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 ?? []);
						}
						$final_pick = array("" => "---- $label_name ----") + $final_pick;
						$this->master_pick[$label_id]   = $final_pick;
						//array_unshift($final_pick,"---- $label_name ----");
						$this->all_pick[$prime_form_id] = $final_pick;
					}
				}else
				if($field_type === 9){
					$pick_query = "select $auto_prime_id,$auto_dispaly_value 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, $auto_prime_id);
						$pick_val   = array_column($pick_result, $auto_dispaly_value);
						$final_pick = array_combine( $pick_key ?? [], $pick_val ?? []);
					} 
					$this->master_pick[$label_id]   = $final_pick;
				}
				if(($input_view_type === 1) || ($input_view_type === 2)){
					$this->view_select  .= "$this->prime_table.$label_id,";
					if($search_show === 1){						
						$this->fliter_list[] = array('label_id'=> $label_id, 'label_name'=> $label_name, 'field_isdefault'=> $field_isdefault, 'array_list'=> $final_pick, 'field_type'=> $field_type);
					}
				}
			}
		}
		$this->view_select   = rtrim($this->view_select,',');
		// ONLY FOR EMPLOYEE
		if($this->control_name === "employees"){
			$this->view_select   = $this->view_select .',user_name,password';
		}		
	}
	// PROVIDE MODLE ONLOAD CONDITION & FORMULA
	public function get_condition(){
		$condition_query = 'select * from cw_form_condition_formula  where cond_module_id = "'.$this->control_name.'" and trans_status = "1" and FIND_IN_SET("'.$this->logged_role.'",condition_for)';
		$condition_data   = $this->db->query("CALL sp_a_run ('SELECT','$condition_query')");
		$condition_result = $condition_data->result();		
		$condition_data->next_result();
		$load_script = "";
		foreach($condition_result as $condition){			
			$prime_cond_id         = $condition->prime_cond_id;
			$cond_module_id        = $condition->cond_module_id;
			$condition_label_name  = strtolower(str_replace(" ","_",$condition->condition_label_name));
			$condition_type        = (int)$condition->condition_type;
			$condition_check_form  = explode(",",$condition->condition_check_form);
			$condition_bind_to     = explode(",",$condition->condition_bind_to);
			$on_bind_input   = "";
			$on_change_input = "";
			$on_blur_input   = "";
			
			foreach($condition_check_form as $label_name){				
				$cond_from_query = 'select field_type,label_name from cw_form_setting  where prime_module_id = "'.$this->control_name.'" and label_name in ("'.$label_name.'") ORDER BY input_for,field_sort asc';
				$cond_form_data   = $this->db->query("CALL sp_a_run ('SELECT','$cond_from_query')");
				$cond_form_result = $cond_form_data->result();
				$cond_form_data->next_result();
				$field_type = (int)$cond_form_result[0]->field_type;
				/*============ 
					NOTE:  AUTO COMPLETE BOX & FILE UPLOAD BOX ARE NOT INCLUDED IN ON LOAD SCRIPT
				============*/
				if(($field_type === 1) || ($field_type === 2) || ($field_type === 3) || ($field_type === 11) || ($field_type === 12)){
					$on_bind_input  .= "$label_name,";
				}else
				if(($field_type === 5) || ($field_type === 6) || ($field_type === 7)){
					$on_change_input  .= "$label_name,";
				}
				if($condition_type === 2){
					if(($field_type === 4) || ($field_type === 13)){
						$on_blur_input  .= "$label_name,";
					}
				}
			}
			$check_input = "";
			if($on_bind_input){
				$on_bind_input = rtrim($on_bind_input,',');
				$on_bind_input = str_replace(",",",#",$on_bind_input);
				$on_bind_input = "#".$on_bind_input;
				$check_input .= "$on_bind_input";
			}			
			
			if($on_change_input){
				$on_change_input = rtrim($on_change_input,',');
				$on_change_input = str_replace(",",",#",$on_change_input);
				$on_change_input = "#".$on_change_input;
				if($check_input){
					$check_input .= ",$on_change_input";
				}else{
					$check_input .= "$on_change_input";
				}
				
			}
			
			if($on_blur_input){
				$on_blur_input = rtrim($on_blur_input,',');
				$on_blur_input = str_replace(",",",#",$on_blur_input);
				$on_blur_input = "#".$on_blur_input;
				if($check_input){
					$check_input .= ",$on_blur_input";
				}else{
					$check_input .= "$on_blur_input";
				}
			}
			
			$send_for  = implode(",",$condition_check_form ?? []);
			$send_data = "prime_cond_id:$prime_cond_id,for_input:'$send_for',";
			foreach($condition_check_form as $check_form){
				$send_data .= "$check_form:$('#$check_form').val(),";
			}
			$send_data = "{".rtrim($send_data,',')."}";
			
			//BIND VALUE FROM DATABASE TABLE
			if($condition_type === 1){
				if($on_bind_input){
					$fill_input = "";
					foreach($condition_bind_to as $bind_to){
						$fill_val    = "ui.item.".$bind_to;
						$fill_input .= "$('#$bind_to').val($fill_val);\n";
					}
					$send_url     = site_url("$this->control_name/bind_autocomplete_suggest");
					$load_script .= "$('$on_bind_input').autocomplete({
										 source: function(request, response) {
											$.getJSON('$send_url',{term:request.term, prime_cond_id:$prime_cond_id },response);
										},
										minChars:2,
										autoFocus: true,
										delay:10,
										appendTo: '.modal-content',
										select: function(e, ui) {
											$fill_input
											return false;
										}
									});\n";
				}
				if($on_change_input){
					$fill_input = "";
					foreach($condition_bind_to as $bind_to){
						$fill_val    = "rslt[0].".$bind_to;
						$fill_input .= "$('#$bind_to').val($fill_val);\n";
					}
					
					$send_url  = site_url("$this->control_name/bind_change_suggest");
					$load_script .= "$('$on_change_input').change(function(){
										var isValid = true;
										$('$on_change_input').each(function() {
										  if ($(this).val() === '') {
											isValid = false;
											$(this).addClass('error');
										  }else{
											 $(this).removeClass('error');
										  }
										});
										if(isValid){
											$.ajax({
												type: 'POST',
												url: '$send_url',
												data:$send_data,
												success: function(data) {
													var rslt = JSON.parse(data);
													$fill_input
												}
											});
										}
									});\n";
				}
			}else
			if($condition_type === 2){
				$fill_input = "";
				foreach($condition_bind_to as $bind_to){
					$fill_val    = "rslt.".$bind_to;
					/*if($this->control_name === 'employees'){
						$fill_input .= "$('#$bind_to').val($fill_val);";
					}else{*/
						$fill_input .= "$('#$bind_to').val($fill_val);\n $('#$bind_to').trigger('change');";
					//}
				}
				$send_url      = site_url("$this->control_name/calculation_suggest");
				$encKey        = $this->generateKey();
				$function_info = "function $condition_label_name(){
									var isValid = true;
									$('$check_input').each(function() {
									  if ($(this).val() === '') {
										isValid = false;
										$(this).addClass('error');
									  }else{
										 $(this).removeClass('error');
									  }
									});
									if(isValid){
										var encKey  = '$encKey';
										var encData = encrypt(encKey,$send_data);
										$.ajax({
											type: 'POST',
											url: '$send_url',
											data:encData,
											success: function(data) {
												var rslt = JSON.parse(data);
												$fill_input
											}
										});
									}
								}";
 				if($on_bind_input){
					$load_script .= "$('$on_bind_input').bind('keyup', function(e) {
										$condition_label_name();
									});

									\n";
				}
				if($on_change_input){
					$load_script .= "$('$on_change_input').change(function(){
										$condition_label_name();
									});\n";
				}
				if($on_blur_input){
					$load_script .= "$('$on_blur_input').blur(function(){
										$condition_label_name();
									});\n";
				}
				$load_script .= "\n$function_info\n";
			}
		}
		$url=$this->config("url")."/logout";
		$load_script .= "\nlet status      = document.getElementsByClassName('modal-title')[0];
            window.addEventListener('load', function(e){
                if (navigator.onLine) {
                    //status.innerHTML = 'User is online';
                    status.classList.add('success');
                    status.classList.add('success');
                } else {
                    status.innerHTML = 'Please Check Your Internet Connection...';
                    status.classList.remove('success');
                    status.classList.add('internet_modal_error');                    
                }
            }, false);
            window.addEventListener('online', function(e){
               // status.innerHTML = 'User is back online';
                status.classList.remove('internet_modal_error');
                status.classList.add('success');
                location.reload();
            }, false);            
            window.addEventListener('offline', function(e){
                status.innerHTML = 'Please Check Your Internet Connection...';
                status.classList.remove('success');
                status.classList.add('internet_modal_error');
            }, false);\n
            $('.select2').on('select2:select', function(e){
				 $(this).focus();
			     e.preventDefault(); 
			});			
			\n";
		if($load_script){
			$this->condition_list[] = $load_script;
		}		
	}
	/* ==============================================================*/
	/* =================== BASE FUNCTIONS - END ===================*/
	/* ==============================================================*/
	
	/* ==============================================================*/
	/* ================= CONDITION OPERATION - START ================*/
	/* ==============================================================*/
	//PROVIDE ALL SINGLE BOX AUTOCOMPLETE DROP DOWN
	public function suggest(){
		$encString     = file_get_contents('php://input');
		$_POST         = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..'));
			exit(0);
		}
		$search_term      = $this->input->post_get('term');		
		$prime_form_id    = $this->input->post('prime_form_id');
		// $depen_pick_list  = $this->input->post('depen_pick_list');
		// $depend_hidden_id = $this->input->post('depend_hidden_id');
		// $label_id_val 	  = $this->input->post('label_id'); ,"'.$depend_hidden_id.'"
		$form_query  = 'select * from cw_form_setting where prime_form_id in ("'.$prime_form_id.'") and trans_status = 1';
		$form_data   = $this->db->query("CALL sp_a_run ('SELECT','$form_query')");
		$form_result = $form_data->result_array();
		$form_data->next_result();	
		$form_result = array_reduce($form_result, function($result, $arr){	
		    $result[$arr['prime_form_id']] = $arr;
		    return $result;
		}, array());
		if($form_result[$prime_form_id]){
			$pick_table          = $form_result[$prime_form_id]['pick_table'];
			$pick_list           = $form_result[$prime_form_id]['pick_list'];
			$auto_prime_id       = $form_result[$prime_form_id]['auto_prime_id'];
			$auto_dispaly_value  = $form_result[$prime_form_id]['auto_dispaly_value'];
			$pick_display_value  = $form_result[$prime_form_id]['pick_display_value'];
			//$depand_join 	= "";
			//$depand_where   = "";
			// if((int)$depen_pick_list === 1){
			// 	$pick_table_sec = $form_result[$depend_hidden_id]['pick_table'];
			// 	$depand_tbl1 	= $form_result[$prime_form_id]['table_column1'];
			// 	$depand_tbl2 	= $form_result[$prime_form_id]['table_column2'];
			// 	$field_type 	= $form_result[$depend_hidden_id]['field_type'];
			// 	$depen_pick_type 	= $form_result[$depend_hidden_id]['pick_list_type'];
			// 	$depen_pick_list 	= $form_result[$depend_hidden_id]['pick_list'];
			// 	if((int)$field_type === 5){
			// 		$pick_list_val   = explode(",",$depen_pick_list);
			// 		if((int)$depen_pick_type === 1){
			// 			$depand_display = $pick_list_val[0];
			// 		}else
			// 		if((int)$depen_pick_type === 2){
			// 			$depand_display = $pick_table."_id";
			// 		}
			// 	}else
			// 	if((int)$field_type === 9){
			// 		$depand_display = $form_result[$depend_hidden_id]['auto_prime_id'];
			// 	}
			// 	// $depand_display = $form_result[$depend_hidden_id]['auto_prime_id'];
			// 	$pick_table 	= $this->input->get('pick_table');
			// 	$table_column2 	= $this->input->get('table_column2');
			// 	$pick_tbl_val 	= $this->input->get('pick_tbl_val');
			// 	$depen_select 	= $this->input->get('depen_select');
			// 	$depand_join 	= " inner join $pick_table_sec on $pick_table_sec.$depand_tbl1 = $pick_table.$depand_tbl2";
			// 	$depand_where 	= " and $pick_table_sec.trans_status = 1 and $pick_table_sec.$depand_display = \"$depen_select\"";
			// }
			$where_condition 	   = $this->get_role_based_picklist($prime_form_id,$form_result[$prime_form_id]['prime_module_id']);
			$pick_list 			 = explode(",", $pick_list);
			$pick_list 			 = "$pick_table.".implode(",$pick_table.", $pick_list ?? []);
			$pick_display_value  = explode(",", $pick_display_value);
			$pick_display_value  = "$pick_table.".implode(",$pick_table.", $pick_display_value ?? []);
			$auto_list 	   = "CONCAT(".str_replace(",",'," - ",',$pick_list).") as auto_list";
			$display_list  = "CONCAT(".str_replace(",",'," - ",',$pick_display_value).") as display_list";
			if($auto_prime_id){
				$auto_prime_ids = "$pick_table.$auto_prime_id,";
			}
			if($auto_dispaly_value){
				$auto_dispaly_values = "$pick_table.$auto_dispaly_value,";
			}
			//$depand_join $depand_where
			$suggest_query = "select $auto_prime_ids $auto_dispaly_values $auto_list,$display_list from $pick_table  where $pick_table.trans_status = 1 ";
			$col_list      = explode(",",$pick_list);
			$suggest_query .= " and ";
			$where_query  = "";
			foreach($col_list as $col){
				$search_term = str_replace('"',"~",$search_term);
				$search_term = str_replace("'","`",$search_term);
				$where_query .= $col.' like "%'.$search_term.'%" or ';
			}
			$where_query    = rtrim($where_query," or ");
			$suggest_query .= '('.$where_query.')';
			$suggest_query .= $where_condition;
			$suggest_query .= ' limit 0,50';
			$suggest_data   = $this->db->query("CALL sp_a_run ('SELECT','$suggest_query')");
			$suggest_result = $suggest_data->result();
			$suggest_data->next_result();
			foreach($suggest_result as $result){
				$suggest_prime_id  = $result->$auto_prime_id;
				$suggest_dispaly   = $result->$auto_dispaly_value;
				$suggest_list      = $result->auto_list;
				$suggest_list = str_replace("~",'"',$suggest_list);
				$suggest_list = str_replace("`","'",$suggest_list);
				$suggest_list = str_replace("^","&",$suggest_list);
				$suggest_dispaly_list = $result->display_list;
				$suggest_dispaly_list = str_replace("~",'"',$suggest_dispaly_list);
				$suggest_dispaly_list = str_replace("`","'",$suggest_dispaly_list);
				$suggest_dispaly_list = str_replace("^","&",$suggest_dispaly_list);
				$suggestions[] = array('value' => $suggest_prime_id, 'label' => $suggest_list, 'display_name' => $suggest_dispaly_list);
			}
		}
		if(empty($suggestions)){
			$suggestions[] = array('value' => "0", 'label' => "No data found for this search");
		}
		echo json_encode($suggestions);		
	}
	
	//PROVIDE AUTOCOMPLETE DROP DOWN TO FILL MULTI INPUT BOX
	public function bind_autocomplete_suggest(){
		$search_term      = $this->input->post_get('term');
		$prime_cond_id    = $this->input->post_get('prime_cond_id');
		echo $this->get_bind_final_query("autocomplete",$search_term,$prime_cond_id);
	}
	
	//PROVIDE DATA WHILE ON CHANGE EVENT TO FILL MULTI INPUT BOX
	public function bind_change_suggest(){
		$for_input        = $this->input->post_get('for_input');
		$prime_cond_id    = $this->input->post_get('prime_cond_id');
		$search_term      = $this->input->post_get($for_input);
		echo $this->get_bind_final_query("change",$search_term,$prime_cond_id);		
	}
	// UDY NEED TO REVIEW
	//PROVIDE QUERY AND RESULT ARRAY TO BIND INPUT
	public function get_bind_final_query($from,$search_term,$prime_cond_id){
		/*============ 
			NOTE:  VAR FROM NOT USED MAY CAN USE IN FURTURE PROCESS
		============*/
		$cond_query = 'select * from cw_form_condition_formula  where prime_cond_id = "'.$prime_cond_id.'" and trans_status = 1';
		$cond_data   = $this->db->query("CALL sp_a_run ('SELECT','$cond_query')");
		$cond_result = $cond_data->result();
		$cond_data->next_result();
		$final_qry = "";
		if($cond_result){
			$cond_module_id       = $cond_result[0]->cond_module_id;
			$condition_check_form = $cond_result[0]->condition_check_form;
			$condition_bind_to    = $cond_result[0]->condition_bind_to;
			$condition_table      = $cond_result[0]->condition_table;
			
			$table_query = 'select * from cw_form_table_cond_for  where table_cond_id = "'.$prime_cond_id.'" ORDER BY abs(line_sort) asc';
			$table_data   = $this->db->query("CALL sp_a_run ('SELECT','$table_query')");
			$table_result = $table_data->result();
			$table_data->next_result();
			$line_table_query = "";
			foreach($table_result as $table){
				$line_prime_table = $table->line_prime_table;
				$line_prime_col   = $table->line_prime_col;
				$line_join_type   = $table->line_join_type;
				$line_join_table  = $table->line_join_table;
				$line_join_col    = $table->line_join_col;
				$line_sort        = $table->line_sort;
				
				$module_name      = str_replace("cw_","",$line_prime_table);
				$prime_id         = "prime_".$module_name."_id";
				
				$join_module_name      = str_replace("cw_","",$line_join_table);
				$join_prime_id         = "prime_".$join_module_name."_id";
				if((int)$line_sort === 1){
					$line_table_query .= " $line_prime_table $line_join_type join $line_join_table on $line_join_col = $line_prime_col "; 
				}else{
					$line_table_query .= " $line_join_type join $line_join_table on $line_join_col = $line_prime_col"; 
				}
			}
			if(!$line_table_query){
				$module_name      = str_replace("cw_","",$condition_table);
				$prime_id         = "prime_".$module_name."_id";
				$line_table_query = " $condition_table ";
			}
			
			
			$for_input_query = 'select * from cw_form_for_input  where input_for_cond_id = "'.$prime_cond_id.'" and trans_status = 1';
			$for_input_data   = $this->db->query("CALL sp_a_run ('SELECT','$for_input_query')");
			$for_input_result = $for_input_data->result();
			$for_input_data->next_result();
			$for_line_input_query = "";
			foreach($for_input_result as $for_input){
				$line_input_for       = $for_input->line_input_for;
				$line_input_for_table = $for_input->line_input_for_table;
				$line_input_for_col   = $for_input->line_input_for_col;	
								
				$for_line_input_query .= $line_input_for_col.' like "'.$search_term.'%" or ';
			}
			if($for_line_input_query){
				$for_line_input_query  = " where ". rtrim($for_line_input_query," or ");
			}
			
			$input_query = 'select * from cw_form_bind_input  where input_cond_id = "'.$prime_cond_id.'" and trans_status = 1';
			$input_data   = $this->db->query("CALL sp_a_run ('SELECT','$input_query')");
			$input_result = $input_data->result();
			$input_data->next_result();
			$line_input_query = "";
			foreach($input_result as $input){
				$line_input_bind_to    = $input->line_input_bind_to;
				$line_input_bind_table = $input->line_input_bind_table;
				$line_input_bind_col   = $input->line_input_bind_col;
				
				$select_query  = 'select field_type from cw_form_setting  where prime_module_id = "'.$cond_module_id.'" and label_name = "'.$line_input_bind_to.'"';
				$select_data   = $this->db->query("CALL sp_a_run ('SELECT','$select_query')");
				$select_result = $select_data->result();
				$select_data->next_result();
				$field_type = (int)$select_result[0]->field_type;
				if(($field_type === 4) || ($field_type === 13)){
					$line_input_query .= 'DATE_FORMAT('.$line_input_bind_col.',"%d-%m-%Y") as '.$line_input_bind_to.',';
				}else{
					$line_input_query .= "$line_input_bind_col as $line_input_bind_to,";
				}
			}
			if($line_input_query){
				$line_input_query  = rtrim($line_input_query,',');
			}else{
				$line_input_query  = " * ";
			}
			$final_qry = "select $line_input_query from $line_table_query $for_line_input_query";
		}
		if($final_qry){
			$final_data   = $this->db->query("CALL sp_a_run ('SELECT','$final_qry')");
			$final_result = $final_data->result();
			$final_data->next_result();
			foreach($final_result as $rslt){
				$line = array();
				$lable = "";
				foreach($input_result as $input){
					$line_input_bind_to    = $input->line_input_bind_to;
					$rslt_val = $rslt->$line_input_bind_to;
					$line[$line_input_bind_to] =  $rslt_val;
					if($rslt_val){
						$lable .= "$rslt_val - ";
						}
				}
				$lable  = rtrim($lable," - ");
				$line['value'] = '';
				$line['label'] = $lable;
				$suggestions[] = $line;
			}
		}
		if(empty($suggestions)){
			$suggestions[] = array('value' => "0", 'label' => "No data found for this search");
		}
		return json_encode($suggestions);
	}
	
	//PROVIDE DATA FOR  ONCHANGE CALCUATION
	public function calculation_suggest(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
		$for_input               = $this->input->post_get('for_input');
		$prime_cond_id           = $this->input->post_get('prime_cond_id');	
		$cond_query              = 'select * from cw_form_condition_formula where prime_cond_id = "'.$prime_cond_id.'" and trans_status = 1';		
		$cond_data               = $this->db->query("CALL sp_a_run ('SELECT','$cond_query')");
		$cond_result             = $cond_data->result();
		$cond_data->next_result();	
		$condition_check_form    = explode(",",$cond_result[0]->condition_check_form);
		$condition_bind_to       = $cond_result[0]->condition_bind_to;
		$condition_table         = $cond_result[0]->condition_table;
		$condition_type          = $cond_result[0]->condition_type;
		$is_drop_down            = (int)$cond_result[0]->is_drop_down;
		$cond_drop_down          = $cond_result[0]->cond_drop_down;
		$fianl_result_array      = array();
		if($is_drop_down === 1){
			$search_term         = $this->input->post_get($cond_drop_down);
			$input_query         = 'select * from cw_form_bind_input  where input_cond_id = "'.$prime_cond_id.'" and line_input_bind_table = "'.$search_term.'"';
			$input_data          = $this->db->query("CALL sp_a_run ('SELECT','$input_query')");
			$input_result        = $input_data->result();
			$input_data->next_result();

			$line_input_bind_col = "";
			foreach($input_result as $input){
				$line_input_bind_to   = $input->line_input_bind_to;
				$line_input_bind_col  = $input->line_input_bind_col;
				$line_input_bind_col  = str_replace("~","'",$line_input_bind_col);
				$line_input_bind_col  = str_replace("!",'"',$line_input_bind_col);
				if($line_input_bind_col){
					foreach($condition_check_form as $check_form){
						if(strpos($line_input_bind_col,"@$check_form@") !== false) {
								$value = $this->input->post_get($check_form);
								if(strpos($check_form,"date") !== false) {
									$value = new DateTime($value);
									$value = $value->format("Y-m-d");
									$value = "'$value'";
								}
							$line_input_bind_col = str_replace("@$check_form@",$value, $line_input_bind_col);
						}
					}
					$dynamic_file_name= "calculation_file/".$line_input_bind_to."_".$this->logged_id.".php";
					unlink("$dynamic_file_name");
					$fname = $line_input_bind_to."(){";
					$code = "<?php function $fname $line_input_bind_col }?>";
					fopen("$dynamic_file_name", "w");
					file_put_contents("$dynamic_file_name",$code);
					chmod($dynamic_file_name, 0777);
					require_once("$dynamic_file_name");
					$fianl_result_array[$line_input_bind_to] =  $line_input_bind_to();
					unlink("$dynamic_file_name");
				}
			}
		}else{
			$input_query = 'select * from cw_form_bind_input  where input_cond_id = "'.$prime_cond_id.'"';
			$input_data   = $this->db->query("CALL sp_a_run ('SELECT','$input_query')");
			$input_result = $input_data->result();
			$input_data->next_result();
			$line_input_bind_col = "";
			foreach($input_result as $input){
				$line_input_bind_to    = $input->line_input_bind_to;
				$line_input_bind_col   = $input->line_input_bind_col;
				$line_input_bind_col  = str_replace("~","'",$line_input_bind_col);
				$line_input_bind_col  = str_replace("!",'"',$line_input_bind_col);
				if($line_input_bind_col){
					foreach($condition_check_form as $check_form){
						if(strpos($line_input_bind_col,"@$check_form@") !== false) {
								$value = $this->input->post_get($check_form);
								if(strpos($check_form,"date") !== false) {
									$value = new DateTime($value);
									$value = $value->format("Y-m-d");
									$value = "'$value'";
								}
							$line_input_bind_col = str_replace("@$check_form@",$value, $line_input_bind_col);
						}
					}				
					$dynamic_file_name= "calculation_file/".$line_input_bind_to."_".$this->logged_id.".php";
					unlink("$dynamic_file_name");
					$fname = $line_input_bind_to."(){";
					$code = "<?php function $fname $line_input_bind_col }?>";
					fopen("$dynamic_file_name", "w");
					file_put_contents("$dynamic_file_name",$code);
					chmod($dynamic_file_name, 0777);
					require_once("$dynamic_file_name");
					$fianl_result_array[$line_input_bind_to] =  $line_input_bind_to();
					unlink("$dynamic_file_name");
				}
			}
		}			
		echo json_encode($fianl_result_array);
	}
	
	// UDY NEED TO REVIEW
	/* ==============================================================*/
	/* ================= CONDITION OPERATION - END ==================*/
	/* ==============================================================*/
	
	/* ==============================================================*/
	/* ================== ROWSET OPERATION - START ==================*/
	/* ==============================================================*/
	// ROWSET SAVE
	public function rowset_save(){
		//Encryption
		$encString      = file_get_contents('php://input');
		$_POST          = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
		$view_id         = $this->input->post('view_id');
		$module_id       = $this->input->post('module_id');
		$row_prime_id    = (int)$this->input->post('row_prime_id');
		$row_label_name  = $this->input->post('row_label_name');
		$prime_id        = $this->input->post('prime_id');
		if($prime_id){ //Decryption
			$decRslt     = $this->cryptoDecrypt(base64_decode(urldecode($prime_id)));
			$prime_id    = (int)$decRslt['prime_id'];
			if(!$prime_id){
				echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..'));
				exit(0);
			}
		}		
		$table_name      = $module_id."_".$row_label_name;
		$table_prime     = "prime_".$table_name."_id";
		$table_name      = $this->db->dbprefix($table_name);
		$prime_qry_key   = "prime_".$module_id."_id,";
		$prime_qry_value = '"'.$prime_id.'",';
		$prime_upd_query = "";
		if($module_id === "holiday_entry"){
			$holiday_date = date('Y-m-d',strtotime($this->input->post('holiday_date')));	
			$time_entry_chk_qry = 'select count(*)as entry_count from cw_time_entry where att_date="'.$holiday_date.'" and whole_day_status="p"';
			$time_entry_data = $this->db->query("CALL sp_a_run ('SELECT','$time_entry_chk_qry')");
			$time_entry_rslt = $time_entry_data->result();
			$time_entry_data->next_result();
			$entry_count     = $time_entry_rslt[0]->entry_count;
			if($entry_count > 0){
				echo json_encode(array('success' => FALSE, 'message' => "Time Entry Already Processed for this date...!!"));
				exit(0);
			}
		}else
		// PROFESSIONAL TAX RANGE MODULE TAX RANGE VALIADTE ON BACKEND --AR
		if($this->control_name === 'professional_tax'){
			$earning_from_value       = $this->input->post('earning_range_from');
			$earning_to_value         = $this->input->post('earning_range_to');

			if($earning_from_value !== "" || $earning_to_value !== 0){
				if(intval($earning_to_value) <= intval($earning_from_value)){
					echo json_encode(array('success' => false,'message' => 'Earning end range Must Be Greater than earning start range'));
        			exit(0);
				}
			}
			$check_overlap_query = 'SELECT COUNT(*) as count FROM cw_professional_tax_tax_range  WHERE prime_professional_tax_id = "'.$prime_id.'" AND trans_status = 1 AND prime_professional_tax_tax_range_id !="'.$row_prime_id.'"  AND ( earning_range_from <= "'.$earning_to_value.'"  AND earning_range_to >= "'.$earning_from_value.'")';
			$current_data         = $this->db->query("CALL sp_a_run ('RUN','$check_overlap_query')");
			$current_result       = $current_data ->result();
			$current_data->next_result();
			if($current_result[0]->count > 0){
					echo json_encode(array('success' => false,'message' => 'Data Range Already Exist. please choose correct your range.'));
				exit(0);
			}
		}
		// END PTR -BY AR
		$form_qry  = 'select * from cw_form_setting where prime_module_id = "'.$module_id.'" and  input_for = "'.$view_id.'" and  field_show = "1" and trans_status = 1';
		$form_data = $this->db->query("CALL sp_a_run ('SELECT','$form_qry')");
		$form_result = $form_data->result();
		$form_data->next_result();
		if($module_id === 'employees' && $row_prime_id > 0){
			$row_set_log = array();
		}
		foreach($form_result as $setting){
			$field_type      = $setting->field_type;
			$input_view_type = (int)$setting->input_view_type;
			$label_id        = strtolower(str_replace(" ","_",$setting->label_name));
			$field_isdefault = $setting->field_isdefault;
			$date_type       = $setting->date_type;
			if((int)$field_type === 7){
				$multi_name = $label_id."[]";
				$value = implode(",",$this->input->post($multi_name) ?? []);
			}else{
				$value = $this->input->post($label_id);
			}	
			if((int)$field_type === 4){
				if($value === ""){
					$value = 'NULL';
				}else{
					if((int)$date_type === 1){
						$value = date('Y-m-d',strtotime($value));
					}else{
						$value = $value;
					}
				}				
			}else
			if((int)$field_type === 13){
        		if($value === ""){
					$value = 'NULL';
				}else{
					$value = date('Y-m-d H:i:s',strtotime($value));
				}	
			}else
			if((int)$field_type === 8){//textbox only
				$value = str_replace('"',"~",$value);
				$value = str_replace("'","`",$value);
				
			}else
			if((int)$field_type === 10){//File Upload
				$value 		 		 = $value;
				$remove_upload_fname = "old_".$label_id;
				$remove_upload_file  = $this->input->post($remove_upload_fname);
				if($value !== $remove_upload_file){
					unlink($remove_upload_file);  
				}
			}			
			$prime_qry_key          .= $label_id.",";
			$prime_qry_value        .= '"'.$value.'",';
			$prime_upd_query        .= $label_id.' = "'.$value.'",';
			$exist_qry              .= $label_id.' = "'.$value.'" and ';
			if($module_id === 'employees' && $row_prime_id > 0){
				$row_set_log[$label_id]  = $value;
			}
		}
		$created_on  = date("Y-m-d h:i:s");
		$exist_count = 0;
		if($module_id === 'employees' && $row_prime_id > 0){
			$this->update_row_set_log($row_prime_id,$prime_id,$view_id,$module_id."_".$row_label_name,$row_set_log);
		}
		if((int)$row_prime_id === 0){
			$prime_qry_key     .= "trans_created_by,trans_created_date";
			$prime_qry_value   .= '"'.$this->logged_id.'",'.'"'.$created_on.'"';
			$prime_insert_query = "insert into $table_name ($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;
			$row_set_data = $this->get_row_set_data($view_id,$prime_id);
			echo json_encode(array('success' => TRUE, 'message' => "Successfully added", 'insert_id' => $insert_id, 'row_set_data' => $row_set_data));
		}else{
			$prime_upd_query    .= 'trans_updated_by = "'. $this->logged_id .'",trans_updated_date = "'.$created_on.'"';
			$prime_update_query  = "UPDATE $table_name SET ". $prime_upd_query .' WHERE '. $table_prime .' = "'. $row_prime_id .'"';
			$this->db->query("CALL sp_a_run ('UPDATE','$prime_update_query')");
			$row_set_data = $this->get_row_set_data($view_id,$prime_id);
			echo json_encode(array('success' => TRUE, 'message' => "Successfully updated",'insert_id' => $row_prime_id,'row_set_data' => $row_set_data));
		}
	}	
	//ROW SET EDIT DATA
	public function row_set_edit(){
		//Encryption
		$encString      = file_get_contents('php://input');
		$_POST          = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
		$row_id          = (int)$this->input->post('row_id');
		$view_id         = (int)$this->input->post('view_id');
		$table_name      = $this->input->post('table_name');
		$table_prime_id  =	 "prime_".$table_name."_id";
		$table_name      = $this->db->dbprefix($table_name);

		$controller_name = $this->control_name;
		if($controller_name === "employee_self_portal"){
			$controller_name  = "employees";
		}

		$final_qry  = "select * from $table_name " .' where '.$table_prime_id.' = "'.$row_id.'" and  trans_status = "1"';
		$row_data   = $this->db->query("CALL sp_a_run ('SELECT','$final_qry')");
		$row_result = $row_data->result();
		$row_data->next_result();
		
		$form_qry    = 'select * from cw_form_setting where prime_module_id = "'.$controller_name.'" and  input_for = "'.$view_id.'" and  input_view_type = "3" and trans_status = "1"';
		$form_data   = $this->db->query("CALL sp_a_run ('SELECT','$form_qry')");
		$form_result = $form_data->result();
		$form_data->next_result();
		$rslt_info = array();
		$rslt_info[$table_prime_id] = array('input_value'=>$row_result[0]->$table_prime_id,'field_type'=>1); ;
		foreach($form_result as $form){
			$prime_form_id      = (int)$form->prime_form_id;
			$label_name         = $form->label_name;
			$field_type         = $form->field_type;
			$pick_table         = $form->pick_table;
			$auto_prime_id      = $form->auto_prime_id;
			$auto_dispaly_value = $form->auto_dispaly_value;
			$mandatory_field    = (int)$form->mandatory_field;			
			$input_value        = $row_result[0]->$label_name;
			$date_type      	= $form->date_type;
			if((int)$field_type === 4){
				if((int)$date_type === 1){
					if($input_value === '0000-00-00' || $input_value ==='01-01-1970' || $input_value === 'NULL'){
						$input_value = "";
					}else{
						$input_value = date('d-m-Y',strtotime($input_value));
					}
				}else{
					$input_value = $input_value;
				}
				if($input_value === "01-01-1970" || $input_value === 'NULL' || $input_value === "0000-00-00"){
					$input_value = "";
				}
				$rslt_info[$label_name] = array('input_value'=>$input_value,'field_type'=>$field_type,'mandatory_field'=>$mandatory_field);
			}else
			if((int)$field_type === 13){
				$input_date =  date('d-m-Y',strtotime($input_value));
				if($input_date === "01-01-1970" || $input_date === 'NULL' || $input_date === '' || $input_date === "00-00-0000" || $input_date === '30-11--0001'){
					$input_value = "";
				}else{
					$input_value = $input_value;
				}
				$rslt_info[$label_name] = array('input_value'=>$input_value,'field_type'=>$field_type,'mandatory_field'=>$mandatory_field);
			}else
			if((int)$field_type === 8){
				$input_value = str_replace("~",'"',$input_value);
				$input_value = str_replace("`","'",$input_value);
				$input_value = str_replace("^","&",$input_value);
				$rslt_info[$label_name] = array('input_value'=>$input_value,'field_type'=>$field_type,'mandatory_field'=>$mandatory_field);
			}else
			if((int)$field_type === 9){
				$rslt_info[$label_name] = array('input_value'=>$input_value,'field_type'=>$field_type,'mandatory_field'=>$mandatory_field);
				$pick_query = 'select '.$auto_dispaly_value.' from '.$pick_table.' where '.$auto_prime_id.' = "'.$input_value.'" and trans_status = 1';
				$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
				$pick_result = $pick_data->result();
				$pick_data->next_result();
				$input_value = $pick_result[0]->$auto_dispaly_value;
				$label_name  = $label_name."_hidden_".$prime_form_id;
				$rslt_info[$label_name] = array('input_value'=>$input_value,'field_type'=>$field_type,'mandatory_field'=>$mandatory_field);
			}else
			if((int)$field_type === 10){
				$old_label_name 	        = "old_".$label_name;
				$rslt_info[$label_name]     = array('input_value'=>$input_value,'field_type'=>$field_type,'mandatory_field'=>$mandatory_field);
				$rslt_info[$old_label_name] = array('input_value'=>$input_value,'field_type'=>$field_type,'mandatory_field'=>$mandatory_field);
			}else{
				$rslt_info[$label_name]     = array('input_value'=>$input_value,'field_type'=>$field_type,'mandatory_field'=>$mandatory_field);
			}
		}
		echo json_encode(array('success' => TRUE, 'row_result' => $rslt_info,'table_name'=> $table_name));
	}
	
	//ROW SET REMOVE DATA
	public function row_set_remove(){
		//Encryption
		$encString       = file_get_contents('php://input');
		$_POST           = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
		$row_id           = (int)$this->input->post('row_id');
		$view_id          = (int)$this->input->post('view_id');
		$table_name       = $this->input->post('table_name');
		$prime_id         = $this->input->post('prime_id');
		$table_prime_id   = "prime_".$table_name."_id";
		$table_name       = $this->db->dbprefix($table_name);
		$logged_id        = $this->session->userdata('logged_id');		
		$today_date       = date("Y-m-d h:i:s");
		if($table_name  === 'cw_holiday_entry_holiday_data'){
			$holiday_qry  = 'SELECT * FROM cw_holiday_entry_holiday_data WHERE prime_holiday_entry_holiday_data_id = "'.$row_id.'" AND trans_status = 1';
			$holiday_data = $this->db->query("CALL sp_a_run ('SELECT','$holiday_qry')");
			$holiday_rslt = $holiday_data->result();
			$holiday_data->next_result();
			$holiday_date = date('Y-m-d',strtotime($holiday_rslt[0]->holiday_date));	
			$time_entry_chk_qry = 'SELECT count(*) as entry_count FROM cw_time_entry WHERE att_date="'.$holiday_date.'" AND whole_day_status = "H" ';
			$time_entry_data = $this->db->query("CALL sp_a_run ('SELECT','$time_entry_chk_qry')");
			$time_entry_rslt = $time_entry_data->result();
			$time_entry_data->next_result();
			$entry_count     = $time_entry_rslt[0]->entry_count;
			if((int)$entry_count > 0){
				echo json_encode(array('success' => FALSE, 'msg' => "Time Entry Already Processed for this date...!!"));
				exit(0);
			}		
		}
		$final_qry       = 'UPDATE '.$table_name.' SET trans_updated_by = "'.$logged_id.'",trans_updated_date = "'.$today_date.'" , trans_status = 0 WHERE '.$table_prime_id.' = "'.$row_id.'"';
		$this->db->query("CALL sp_a_run ('SELECT','$final_qry')");
		$row_set_data    = $this->get_row_set_data($view_id,$prime_id);
		echo json_encode(array('success' => TRUE, 'msg' => "Remove Successfully",'row_set_data' => $row_set_data));
	}
	//PROVIDE ROWSET DATA BY ID
	public function get_row_set_data($view_id,$prime_id){
		$controller_name  = $this->control_name;
		if($controller_name === "employee_self_portal"){
			$controller_name  = "employees";
		}
		$view_qry    = 'select * from cw_form_view_setting where prime_form_view_id = "'.$view_id.'" and prime_view_module_id = "'.$controller_name.'" and  form_view_type = "3" and trans_status = 1';
		$view_data   = $this->db->query("CALL sp_a_run ('SELECT','$view_qry')");
		$view_result = $view_data->result();
		$view_data->next_result();
		$prime_form_view_id   = $view_result[0]->prime_form_view_id;
		$prime_view_module_id = $view_result[0]->prime_view_module_id;
		$form_view_label_name = $view_result[0]->form_view_label_name;
		
		$div_id       	 = $form_view_label_name."_div_".$prime_form_view_id;
		$table_id        = $form_view_label_name."_tbl_".$prime_form_view_id;
		$table_name      = $controller_name."_".$form_view_label_name;
		$row_prime_id    = "prime_".$table_name."_id";
		$table_name      =  $this->db->dbprefix($table_name);
		$table_prime_id  = "prime_".$controller_name."_id";

		$access_data    	  = $this->session->userdata('access_data');
		$access_update  	  = (int)$access_data[$this->control_name]['access_update'];
		$access_delete  	  = (int)$access_data[$this->control_name]['access_delete'];
		
		$form_qry    = 'select prime_form_id,view_name,label_name,field_type,date_type,pick_list_type,pick_list,pick_table,auto_prime_id,auto_dispaly_value from cw_form_setting where prime_module_id = "'.$controller_name.'" and  input_for = "'.$prime_form_view_id.'" and  input_view_type = "3" and table_show = "1" and trans_status = "1" order by abs(field_sort)';
		$form_data   = $this->db->query("CALL sp_a_run ('SELECT','$form_qry')");
		$form_result = $form_data->result();
		$form_data->next_result();
		$table_head = array();
		$thead_line = "";
		$select_query = "$table_name.$row_prime_id,$table_name.$table_prime_id,";

		foreach($form_result as $form){
			$prime_form_id  = (int)$form->prime_form_id;
			$view_name      = $form->view_name;
			$label_name     = $form->label_name;
			$field_type     = (int)$form->field_type;
			$pick_list_type = (int)$form->pick_list_type;
			$pick_list      = $form->pick_list;
			$pick_table     = $form->pick_table;
			$auto_prime_id      = $form->auto_prime_id;
			$auto_dispaly_value = $form->auto_dispaly_value;
			$date_type 	 		= $form->date_type;
			if((int)$field_type === 4){
				if((int)$date_type === 1){
					$select_query .= 'DATE_FORMAT('.$table_name.'.'.$label_name.', "%d-%m-%Y") as '.$label_name.' , ';
				}else{
					$select_query .= "$table_name.$label_name , ";
				}
			}else
			if((int)$field_type === 13){
				$select_query .= 'DATE_FORMAT('.$table_name.'.'.$label_name.', "%d-%m-%Y H:i:s") as '.$label_name.' , ';
			}else
			if(($field_type === 5) || ($field_type === 7)){
				if($pick_list_type === 1){
					if($label_name === "component_value" && $this->control_name === "holiday_entry"){
						/* CUTOME CODE FOR HOLIDAY ENTRY MODULE START*/
						$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 = 2 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];
						/* CUTOME CODE FOR HOLIDAY ENTRY MODULE END */
					}else
					// =================== DYNAMIC PICKLIST ADDED BASED CLAIM LIMIT BASED VALUE ================
					if($label_name === "claim_component" && $this->control_name === "claim_type"){
						$company_info   	   = $this->company_info();
						$claim_limit_based_on  = $company_info[0]->claim_limit_based_on;
						$form_qry = "SELECT pick_list, pick_table, auto_prime_id, auto_dispaly_value FROM cw_form_setting WHERE trans_status = '1' AND label_name = '$claim_limit_based_on' AND prime_module_id = 'employees' ";
						$form_data        = $this->db->query($form_qry);
						$form_result      = $form_data->result_array();
						$form_data->next_result();
						$pick_list        = $form_result[0]['pick_list'];
						$pick_table       = $form_result[0]['pick_table'];
						$pick_list_val    = explode(",", $pick_list);
						$pick_list_val_1  = $pick_list_val[0];
						$pick_list_val_2  = $pick_list_val[1];

					}else{
						$pick_list_val   = explode(",",$pick_list);
						$pick_list_val_1 = $pick_list_val[0];
						$pick_list_val_2 = $pick_list_val[1];
					}
					$pick_query_as = $pick_table."_".$prime_form_id;
					$select_query .= "group_concat(distinct $pick_query_as.$pick_list_val_2) as $label_name , ";
					$pick_query .= " left join $pick_table as $pick_query_as on FIND_IN_SET( $pick_query_as.$pick_list_val_1,$table_name.$label_name )";
				}else
				if($pick_list_type === 2){ 
					$pick_list_val_1 = $pick_table."_id";
					$pick_list_val_2 = $pick_table."_value";
					$pick_list_val_3 = $pick_table."_status";
					
					$pick_query_as = $pick_table."_".$prime_form_id;
					$select_query .= "$pick_query_as.$pick_list_val_2 as $label_name , ";
					$pick_query   .= " left join $pick_table as $pick_query_as on $pick_query_as.$pick_list_val_1 = $table_name.$label_name ";
				}
			}else
			if($field_type === 9){
				$pick_query_as = $pick_table."_".$prime_form_id;
				$select_query .= "$pick_query_as.$auto_dispaly_value as $label_name,";
				$pick_query   .= " left join $pick_table as $pick_query_as on $pick_query_as.$auto_prime_id = $table_name.$label_name ";
			}else{
				$select_query .= "$table_name.$label_name , ";
			}
			$table_head[] = $label_name;
			$thead_line  .= "<th>$view_name</th>";
		}
		$thead = "<tr>$thead_line<th>Option</th></tr>";
		
		$select_query = rtrim($select_query,',');
		$select_query = rtrim($select_query,' , ');
		if($table_name === "cw_holiday_entry_holiday_data"){
			$order_qry = 'order by cw_holiday_entry_holiday_data.holiday_date desc';
		}else{
			$order_qry = 'order by abs('.$table_name.'.'.$row_prime_id.') desc';
		}
		
		$grp_by       ="group by $row_prime_id";
		$final_qry    = "select $select_query from $table_name $pick_query " .' where '.$table_name.'.'.$table_prime_id.' = "'.$prime_id.'" and '.$table_name.'.trans_status = "1" '.$grp_by.' '.$order_qry ;
		$row_data     = $this->db->query("CALL sp_a_run ('SELECT','$final_qry')");
		$row_result   = $row_data->result();
		$row_data->next_result();
		$tr_line = "";
		foreach($row_result as $data){
			$td_line = "";
			foreach($table_head as $label){
				$datas_exp        = $data->$label;
				$rowset_form_info = $this->get_rowset_form_info();
				$field_type       = $rowset_form_info[$label]['field_type'];
				$value            = $data->$label;
				
				if((int)$field_type === 4 || (int)$field_type === 13){
					if($value === "00-00-0000" || $value === 'NULL' || $value === "00-00-0000 00:00:00"){
						$td_line .= "<td></td>";
					}else{
						$td_line .= "<td>$value</td>";
					}
				}else
				if((int)$field_type === 8){//textbox only
					$value    = str_replace("~",'"',$value);
					$value    = str_replace("`","'",$value);
					$value    = str_replace("^","&",$value);
					$td_line .= "<td>$value</td>";
				}else
				if((int)$field_type === 10){
					if($datas_exp === "" || $datas_exp === NULL){
						$td_line .= "<td>No Preview Available</td>";
					}else{
						$file_ext_type = preg_replace('/^.*\.([^.]+)$/D', '$1', $value);
						//PDF FILE NAME DISPLAY -> NB[19-08-2023]
						$split_values  = explode("/", $value);
						$file_name     = $split_values[2];
						$file_name     = preg_replace('/^\d+_/', '', $file_name); 
						$file_name     = strtolower($file_name); 
						if($file_ext_type === 'zip' || $file_ext_type === 'rar' || $file_ext_type === 'eml' || $file_ext_type === 'msg'){
							$td_line  .= "<td><a href='$datas_exp' format.pdf = '' target='_blank' download = $file_name style='cursor: pointer;color:blue;'><i class='fa fa-download' style='margin-right:5px' aria-hidden='true'></i>$file_name</a></td>";
						}else{
							$td_line  .= '<td><a onclick="view_upload_file(\''.$value.'\', \''.$file_ext_type.'\');" style="cursor: pointer; color: blue;margin-right:5px"><i class="fa fa-folder-open" style="margin-right:5px"aria-hidden="true"></i>'.$file_name.'</a></td>';
						}
					}
				}else{
					$td_line .= "<td>$value</td>";					
				}
			}
			$row_id           = $data->$row_prime_id;
			$tab_name         = $controller_name."_".$form_view_label_name;
			$illustration_btn = "";
			if($form_view_label_name === "eligibility_information"){
				$illustration_btn   = "<a class='btn btn-edit btn-xs row_btn' onclick = add_illustration('$row_id','$tab_name','$prime_form_view_id');>Illustration</a>";
			}
			if((int)$access_update === 0){
				$edit_btn   = "";
			}else{
				$edit_btn   = "<a class='btn btn-edit btn-xs row_btn' onclick = row_set_edit('$row_id','$tab_name','$prime_form_view_id','$prime_id');>Edit</a>";
			}
			if((int)$access_delete === 0){
				$remove_btn = "";
			}else{
				$remove_btn = "<a class='btn btn-danger btn-xs row_btn' onclick = row_set_remove('$row_id','$tab_name','$prime_form_view_id','$prime_id');>Delete</a>";
			}
			$tr_line .= "<tr>$td_line<td>$illustration_btn $edit_btn $remove_btn</td></tr>";
		}
		$row_set_view = "<table id='$table_id' class='table table-bordered' style='background-color: #FFFFFF; box-shadow: none;'>
							<thead>$thead</thead>
							<tbody>$tr_line</tbody>
						</table>";
		return array('div_id' => $div_id, 'table_id' => $table_id,'row_set_view'=>$row_set_view);
	}
	
	public function update_row_set_log($row_prime_id,$prime_id,$view_id,$table_prime,$row_set_log){
		$logged_id     = $this->session->userdata('logged_id');
		$created_date  = date("Y-m-d H:i:s");
		$label_name    = array_keys($row_set_log);
		$label_value   = implode(",",$label_name ?? []);	
		$table_name    = $this->db->dbprefix($table_prime);	
		$table_prime   = "prime_".$table_prime."_id";
		$select_query  = "select $label_value from $table_name where $table_prime = \"$row_prime_id\"";
		$select_info   = $this->db->query("CALL sp_a_run ('RUN','$select_query')");
		$select_result = json_decode(json_encode($select_info->row()),true);
		$select_info->next_result();
		$result           = array_diff($row_set_log,$select_result);
		$prime_qry_value  = '';
		$prime_qry_key    =
		"prime_employees_id,row_set_view_id,row_set_view_name,row_prime_id,label_name,old_value,new_value,trans_created_by,trans_created_date";
		foreach($result as $key => $value){
			$check_value      = $select_result[$key];
			$prime_qry_value .= "(\"$prime_id\",\"$view_id\",\"$table_name\",\"$row_prime_id\",\"$key\",\"$check_value\",\"$value\",\"$logged_id\",\"$created_date\"),";
		}
		if($prime_qry_value !== ''){
			$prime_qry_value = rtrim($prime_qry_value,',');
			$prime_insert_query = "insert into cw_row_set_log ($prime_qry_key) values $prime_qry_value";
			$insert_info        = $this->db->query("CALL sp_a_run ('INSERT','$prime_insert_query')");
			$insert_result      = $insert_info->result();
			$insert_info->next_result();
		}
	}
	/* ==============================================================*/
	/* =================== ROWSET OPERATION - END ===================*/
	/* ==============================================================*/
	
	/* ==============================================================*/
	/* ================== IMPORT OPERATION - START ==================*/
	/* ==============================================================*/
	//SAVE IMPORT FILE PATH
	public function save_import(){
		//Encryption
		$encString      = file_get_contents('php://input');
		$_POST          = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
		$module_id        = $this->input->post('module_id');
		$import_type      = $this->input->post('import_type');
		$excel_format     = $this->input->post('excel_format');
		$excel_file_path  = $this->input->post('excel_file_path');
		$excel_sheet_name = $this->input->post('excel_sheet_name');
		$excel_start_row  = $this->input->post('excel_start_row');
		$excel_end_row    = $this->input->post('excel_end_row');
		$logged_id        = $this->session->userdata('logged_id');
		$today_date       = date("Y-m-d H:i:s");
		if($module_id === "employees"){
			$import_type_val = $import_type;
		}else{
			$import_type_val = 1;
		}
		$import_query = 'insert into cw_import (import_type,module_id,excel_format,excel_file_path,excel_sheet_name,excel_start_row,excel_end_row,trans_created_by,trans_created_date) value ("'.$import_type.'","'.$module_id.'","'.$excel_format.'","'.$excel_file_path.'","'.$excel_sheet_name.'","'.$excel_start_row.'","'.$excel_end_row.'","'.$logged_id.'","'.$today_date.'")';
		$import_info   = $this->db->query("CALL sp_a_run ('INSERT','$import_query')");
		$import_result = $import_info->result();
		$import_info->next_result();
		$import_id = $import_result[0]->ins_id;
		if($module_id === "employees"){
			echo $this->do_excel_emp_import($import_id);
			//FUNCTION WORKING INPROGESS (DON'T DELETE)
			// echo $this->do_csv_emp_import($import_id);
		}else
		if($module_id === "loan"){
			echo $this->do_loan_excel_import($import_id);
		}else
		if($module_id === "time_log"){
		 	echo $this->do_excel_timelog_import($import_id);
		}else
		if($module_id === "leave_entry"){
		 	echo $this->do_excel_leave_import($import_id);
		}else
		if($module_id === "shift_import"){
		 	echo $this->do_excel_shift_import($import_id);
		}else
		if($module_id === "weekoff_import"){
		 	echo $this->do_excel_weekoff_import($import_id);
		}else
		if($module_id === "overtime_request"){
			$category         = $this->input->post('category');
			$process_month    = $this->input->post('process_month');
		 	echo $this->do_excel_ot_request_import($import_id,$category,$process_month);
		}else
		if($module_id === "manual_punch_entry"){
			$category         = $this->input->post('category');
			$process_month    = $this->input->post('process_month');
		 	echo $this->do_excel_manual_punch_import($import_id,$category,$process_month);
		}else
		if($module_id === "direct_leave_entry"){ //Created for TCL by GV 
		 	echo $this->do_excel_direct_hr_import($import_id);
		}else
		if($module_id === "offline_tds_entry"){
 			echo $this->do_excel_offline_tds_import($import_id);
		}else
		if($module_id === "shift_config" || $module_id === "weekoff_config"){
 			echo $this->do_config_import($import_id);
		}else{
			echo $this->do_excel_import($import_id,$import_type);
		}
	}
	public function do_excel_emp_import($import_id){
		if($import_id < 0){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}
		$excel_path_qry             = 'select * from cw_import where import_id = "'.$import_id.'"';
		$excel_path_info            = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
		$excel_path_result          = $excel_path_info->result();
		$excel_path_info->next_result();
		if(!$excel_path_result){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}else{
			$excel_file_path        = $excel_path_result[0]->excel_file_path;
			$module_id              = $excel_path_result[0]->module_id;
			$import_type            = (int)$excel_path_result[0]->import_type;
			$excel_format           = $excel_path_result[0]->excel_format;
			$excel_sheet_name       = (int)$excel_path_result[0]->excel_sheet_name;
			$excel_row_start        = (int)$excel_path_result[0]->excel_start_row;
			$excel_row_end          = (int)$excel_path_result[0]->excel_end_row;
			$format_qry 	        = 'select * from cw_util_excel_format where prime_excel_format_id = "'.$excel_format.'" and cw_util_excel_format.trans_status = 1';
			$format_info            = $this->db->query("CALL sp_a_run ('SELECT','$format_qry')");
			$format_rslt            = $format_info->result();
			$format_info->next_result();
			if(!$format_rslt){
				return json_encode(array('success' => false, 'message' => "Please add excel format before import"));
			}else{
				$exist_column_name 	= explode(",",$format_rslt[0]->exist_column_name);
				$excel_format_qry 	= 'select IFNULL(pick_list_import,0) as pick_list_import,input_view_type,field_length,label_name,unique_field,view_name,duplicate_data,field_length,picklist_data,field_type,date_type,text_type,pick_table,pick_list_type,pick_list,mandatory_field,field_isdefault,excel_line_column_name,excel_line_value from cw_util_excel_format_line inner join cw_form_setting on label_name = excel_line_column_name where excel_line_module_id = "'.$module_id.'" and prime_excel_format_id = "'.$excel_format.'" and cw_form_setting.prime_module_id = "'.$module_id.'" and cw_util_excel_format_line.trans_status = 1';		
				$excel_format         = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
				$excel_format_result  = $excel_format->result();
				$excel_format->next_result();
				if(!$excel_format_result){
					return json_encode(array('success' => false, 'message' => "Please map excel cell column before import"));
				}else{
					try{
						$excel_obj = \PhpOffice\PhpSpreadsheet\IOFactory::load($excel_file_path); // [MS 18-11-2024]
					}catch(Exception $e){
						die('Error loading file "' . pathinfo($excel_file_path, PATHINFO_BASENAME). '": ' . $e->getMessage());
						return json_encode(array('success' => false, 'message' => "Invalid file or path"));
					}
					$sheet 			  = $excel_obj->getSheet($excel_sheet_name);
					if($excel_row_end){
						$total_rows   = $excel_row_end;
					}else{
						$total_rows   = $sheet->getHighestRow();
					}
					$highest_column   = $sheet->getHighestColumn();
					//DYNAMIC INPUT VALIDATIONS !
					$error_data 	  =  $this->validate_excel_import_dynamic($excel_format_result,$total_rows,$excel_row_start,$sheet,$import_type);
					$err_column_count = count($error_data['error'] ?? []);
					if((int)$err_column_count > 0){
						$table_info   = $this->get_excel_error_ui($error_data);
						echo json_encode(array('success'=>false,'message'=>'Error in your Excel data.','table_info'=>$table_info));
						exit(0);
					}else{
						//STATIC INPUT VALIDATIONS !
						$rowwise_result      = $this->validate_excel_import_static($sheet,$excel_obj,$import_type,$excel_format_result,$excel_row_start,$total_rows);
						$err_column_array    = $rowwise_result['err_column_array'];
						$err_column_tabview  = $rowwise_result['err_column_tabview'];
						$err_column_count    = count($err_column_array['error'] ?? []);
						$err_column          = implode(",",(array_unique($err_column_array['error'] ?? [])) ?? []);
						if((int)$err_column_count > 0){
							$table_info      = $this->get_excel_error_ui($err_column_tabview);
							echo json_encode(array('success'=>false,'message'=>"Row wise Error",'table_info'=>$table_info));
							exit();
						}else{
							//FINAL IMPORT !
							$final_result    = $this->emp_final_excel_import($module_id,$sheet,$import_type,$excel_format_result,$excel_row_start,$total_rows,$exist_column_name);
						}
					}
				}							
			}		
		}
	}
	//VALIDATING INPUTS BASED ON FIELDTYPES!
	public function validate_excel_import_dynamic($excel_format_result,$total_rows,$excel_row_start,$sheet,$import_type){
		$db_name             = $this->config->item("db_name");
		$err_column_array    = array();
		$err_column_tabview  = array();
		//INACTIVE AND RESIGNED 
		$emp_code_qry         = 'select employee_code,termination_status from cw_employees where trans_status =1';
		$emp_code_data        = $this->db->query("CALL sp_a_run ('SELECT','$emp_code_qry')");
		$emp_code_data_result = $emp_code_data->result_array();
		$emp_code_data->next_result();
		$emp_code_data_result = array_map(function($v){
			$return_array     = array();
			$return_array['termination_status'] = $v['termination_status'];
			$return_array['employee_code']      = $v['employee_code'];
		    return $return_array;
		}, $emp_code_data_result);
		$emp_code_data_result = array_column($emp_code_data_result,'termination_status','employee_code');

		//VALIDATION FUNCTION STARTS -> NB[07-10-23]
		foreach($excel_format_result as $excel_info){   
			$field_isdefault         = (int)$excel_info->field_isdefault;
			$mandatory_field         = (int)$excel_info->mandatory_field;
			$field_type              = (int)$excel_info->field_type;
			$excel_line_column_name  = $excel_info->excel_line_column_name;
			$excel_line_value        = $excel_info->excel_line_value;
			$view_name               = $excel_info->view_name;
			$pick_table              = $excel_info->pick_table;
			$pick_list_type          = (int)$excel_info->pick_list_type;
			$pick_list               = $excel_info->pick_list;
			$picklist_data           = (int)$excel_info->picklist_data;
			$pick_list_import        = (int)$excel_info->pick_list_import;
			$text_type       		 = (int)$excel_info->text_type;
			$date_type       		 = (int)$excel_info->date_type;
			$duplicate_data          = (int)$excel_info->duplicate_data;
			$field_length            = (int)$excel_info->field_length;
			$input_view_type         = (int)$excel_info->input_view_type;
			// THEY CONTROL FORMULA AND FORMAT WILL GET RAW DATAS TO CHCEKS _ARN 22-11-2025
			$common_multi_cell_value = $sheet->rangeToArray("$excel_line_value$excel_row_start:$excel_line_value$total_rows", NULL, FALSE, FALSE, TRUE);  
			$i = $excel_row_start;	
			foreach($common_multi_cell_value as $common_value){ 
				foreach($common_value as $col_key =>$cell_value){

					// IF FORMULA LIKE VALUES COMES ON EXCEL SHEET WILL THROWING ERROR
					$cellObj = $sheet->getCell("$col_key$i");
					//  CHECK IF FORMULA
					if($cellObj->isFormula()){
						$err_column_array['error']["$excel_line_value$i"] = $view_name;
						$msg_line = "[$cell_value] - Formula not allowed in this field.";
						$err_column_tabview['error']["$excel_line_value$i"] = $view_name." ".$msg_line;
						$i++;
						continue; // skip further validation
					}


					//FOR JUNK CHARACTERS !
					if($cell_value){  
						if((int)$this->validatejunkchar($cell_value) === 0){
							$err_column_array['error']["$excel_line_value$i"]   = $view_name;
							$msg_line = "[$cell_value] - Invalid junk value detected.!";
							$err_column_tabview['error']["$excel_line_value$i"] = $view_name." ".$msg_line;
						}
					}
					//CHANGING "",'',& TO ~,^,`.
					if($cell_value){
						$cell_value = str_replace('"',"~",$cell_value);
						$cell_value = str_replace("'","`",$cell_value);
					}
					//FIELD TYPE VALIDATION STARTS !
					if(empty($cell_value) && $mandatory_field === 1){
						$err_column_array['error']["$excel_line_value$i"]    = $view_name;
						$msg_line      = " - Columns are required and they are empty. Please check.!";
						$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
					}elseif($excel_line_column_name === "employee_code" && $import_type === 2){ 
						$employee_code = $cell_value;   //FOR RESIGNED AND INACTIVE
						if(!isset($emp_code_data_result[$cell_value])){
							$err_column_array['error']["$excel_line_value$i"]    = $view_name;
							$msg_line  = "[$cell_value] Not found in employee master. Please check.";
							$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
						}
						// elseif($db_name !== "rad_hrms_db"){
						// 	if($emp_code_data_result[$cell_value] === "1"){
						// 		$err_column_array['error']["$excel_line_value$i"]    = $view_name;
						// 		$msg_line  = "[$cell_value] Already resigned. Please check.!";
						// 		$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
						// 	}
						// }
					}elseif($field_type === 1 ){
						if($text_type === 1){   //ONLY TEXT
							$excel_string     = $sheet->getCell("$col_key$i")->getValue();
							if(!empty($excel_string)){
								if((int)$this->validateString($excel_string) === 0){
									$err_column_array['error']["$excel_line_value$i"]    = $view_name;
									$msg_line = "[$cell_value] - Invalid... Please map The correct Text";
									$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
								}
							}
						}elseif($text_type  === 3){  //FOR INTEGER			
							$excel_int = $sheet->getCell("$col_key$i")->getValue();
							if(!empty($excel_int)){
								if((int)$this->validateinteger($excel_int) === 0){
									$err_column_array['error']["$excel_line_value$i"]    = $view_name;
									$msg_line = "[$cell_value] - Invalid... Please map The  correct Integer";
									$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
								}
							}
						}
					}elseif($field_type === 2){  	// FOR DECIMAL
						$excel_float = $sheet->getCell("$col_key$i")->getValue();
						if(!is_numeric($excel_float) && !empty($excel_float)){
							if ((int)$this->validateDecimal($excel_float) === 0) {
								$err_column_array['error']["$excel_line_value$i"]    = $view_name;
								$msg_line = "[$cell_value] - Invalid... Please map the correct Decimal";
								$err_column_tabview['error']["$excel_line_value$i"]  = $view_name . " " . $msg_line;
							}
						}
					}elseif($field_type === 3){  //FOR INTEGER			
						$excel_int = $sheet->getCell("$col_key$i")->getValue();
						if(!empty($excel_int)){
							if(!is_numeric($excel_int)){
								$err_column_array['error']["$excel_line_value$i"]    = $view_name;
								$msg_line = "[$cell_value] - Invalid... Please map The  correct Integer";
								$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
							}
						}
					}elseif($field_type === 4){							
						if($date_type   === 1){  //FOR DATE-MONTH-YEAR
							$format      = $sheet->getCell("$col_key$i")->getStyle()->getNumberFormat()->getFormatCode();
							//Based on excel cell format converting to dd-mm-yyyy 
							if($format  === "General" || $format === "@"){
								$cell        = $sheet->getCell("$col_key$i"); 
								$excelDate   = $cell->getFormattedValue();
							}else
							if($format === "m/d/yyyy" || $format === "[$-14009]dd/mm/yyyy" || $format === "[$-F800]dddd\,\ mmmm\ dd\,\ yyyy" || $format === "[$-14009]dd/mm/yyyy;@" || $format === "[$-4009]dd/mm/yyyy;@"){
								$excelDate   = trim(date('d-m-Y',Date::PHPToExcel($sheet->getCell("$col_key$i")->getValue())));	
							}else{
    							$err_column_array['error']["$excel_line_value$i"]   = $view_name;
    							$msg_line    = " Invalid... Please check the format and try again.";
    							$err_column_tabview['error']["$excel_line_value$i"] = $view_name . " " . $msg_line;
    						}
							if($excelDate){
								if($excelDate === "31-01-1900"){
									$err_column_array['error']["$excel_line_value$i"]   = $view_name;
									$msg_line = "- Invalid Date. Please change it!";
									$err_column_tabview['error']["$excel_line_value$i"] = $view_name." ".$msg_line;
								}elseif((int)$this->validateDATE($excelDate) === 0){
									$err_column_array['error']["$excel_line_value$i"]   = $view_name;
									$msg_line = "[$excelDate] - Invalid ... Please map the correct DATE format (DD-MM-YYYY)";
									$err_column_tabview['error']["$excel_line_value$i"] = $view_name." ".$msg_line;
								}
							}
						}
						else
						if($date_type === 2){  //FOR MONTH-YEAR
							$cell             = $sheet->getCell("$col_key$i");
							$excelDateValue   = $cell->getFormattedValue();
							if(!empty($excelDateValue)){
								if ((int)$this->validateMonthYear($excelDateValue) === 0){
									$err_column_array['error']["$excel_line_value$i"]   = $view_name;
									$msg_line = "[$cell_value] - Invalid ... Please map the correct MONTH-YEAR format (MM-YYYY)";
									$err_column_tabview['error']["$excel_line_value$i"] = $view_name." ".$msg_line;
								}
							}
						}else
						if($date_type === 3){  //FOR YEAR
							$format         = $sheet->getCell("$col_key$i")->getStyle()->getNumberFormat()->getFormatCode();
							$cell 			= $sheet->getCell("$col_key$i");
							$excelDateValue = $cell->getFormattedValue();
							if(!empty($excelDateValue)){
								if ((int)$this->validateYear($excelDateValue) === 0){
									$err_column_array['error']["$excel_line_value$i"]   = $view_name;
									$msg_line = "[$cell_value] - Invalid ... Please map the correct YEAR format (YYYY)";
									$err_column_tabview['error']["$excel_line_value$i"] = $view_name." ".$msg_line;
								}
							}
						}
					}elseif($field_type === 5 || $field_type === 7){  //FOR PICKLIST
						//MANDATORY FIELDS
						if(($mandatory_field === 1) || ($picklist_data === 1)){  
							if($pick_list_type === 1){ //from table 
								$pick_list_val   = explode(",",$pick_list);
								$pick_list_val_1 = $pick_list_val[0];
								$pick_list_val_2 = $pick_list_val[1];
								$pick_list_where = $pick_list_val_2.' = "'.$cell_value.'"';
								if($pick_list_import === 1){
									$pick_list_where  = $pick_list_val_1.' = "'.$cell_value.'"';
								}
								//Checking if the value is present in the select table.
								$pick_query      = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_where;	
								$pick_data  	 = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
								$pick_result	 = $pick_data->result();
								$pick_count 	 = $pick_data->num_rows();
								$pick_data->next_result();
								if((int)$pick_count === 0){
									$err_column_array['error']["$excel_line_value$i"] = $view_name;
									$msg_line    = "- Invalid data[$cell_value] is present... Please check and try again.!";
									$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
								}else{ 
									//Tax Range is checking for your mention location
									if($pick_table === "cw_professional_tax_location"){
										$tax_location_range     = $pick_result[0]->$pick_list_val_1;
										$tax_location_range_qry = 'select count(*) as rslt_range from cw_professional_tax where trans_status = 1 and location = "'.$tax_location_range.'"';
										$tax_range_data         = $this->db->query("CALL sp_a_run ('SELECT','$tax_location_range_qry')");
										$tax_range_data_result  = $tax_range_data->result();
										$tax_range_data->next_result();
										$range_count            = $tax_range_data_result[0]->rslt_range;
										if((int)$range_count   === 0){
											$tax_sts            = 1;
											$tax_location       = $cell_value;
											$err_column_array['error']["$excel_line_value$i"]    = $view_name;
											$msg_line           = "$cell_value range not present please check it?";
											$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
										}
									}
								}
							}elseif($pick_list_type === 2){  //new picklist
								$pick_list_val_2 = $pick_table."_value";
								//checking if the value present in the picklist value input.
								$pick_query      = 'select count(*) as rslt_count from '.$pick_table.' where '.$pick_list_val_2.' = "'.$cell_value.'"';
								$pick_data       = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
								$pick_result     = $pick_data->row();
								$pick_data->next_result();
								$pick_count      = (int)$pick_result->rslt_count;
								if((int)$pick_count === 0){
									$err_column_array['error']["$excel_line_value$i"]    = $view_name;
									$msg_line    = "Invalid value[$cell_value]... Please check and try again.!";
									$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
								}
							}  
						} //NON-MANDATORY FIELDS ONLY AUTO PRIME ID
						elseif($pick_list_import === 1){
							if($pick_list_type === 1){ //from table 
								$pick_list_val   = explode(",",$pick_list);
								$pick_list_val_1 = $pick_list_val[0];
								$pick_list_val_2 = $pick_list_val[1];
								$pick_list_where = $pick_list_val_2.' = "'.$cell_value.'"';
								if($pick_list_import === 1){
									$pick_list_where  = $pick_list_val_1.' = "'.$cell_value.'"';
								}
								//Checking if the value is present in the select table.
								$pick_query      = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_where;	
								$pick_data  	 = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
								$pick_result	 = $pick_data->result();
								$pick_count 	 = $pick_data->num_rows();
								$pick_data->next_result();
								if((int)$pick_count === 0){
									$err_column_array['error']["$excel_line_value$i"] = $view_name;
									$msg_line    = "- Invalid data is present... Please check and try again.!";
									$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
								}
							}elseif($pick_list_type === 2){  //new picklist
								$pick_list_val_2 = $pick_table."_value";
								//checking if the value present in the picklist value input.
								$pick_query      = 'select count(*) as rslt_count from '.$pick_table.' where '.$pick_list_val_2.' = "'.$cell_value.'"';
								$pick_data       = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
								$pick_result     = $pick_data->row();
								$pick_data->next_result();
								$pick_count      = (int)$pick_result->rslt_count;
								if((int)$pick_count === 0){
									$err_column_array['error']["$excel_line_value$i"]    = $view_name;
									$msg_line    = "Invalid value[$cell_value]... Please check and try again.!";
									$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
								}
							}
						}
					}elseif($field_type === 11 ){	 //FOR MOBILE NUMBER		
						$excel_mobile     = $sheet->getCell("$col_key$i")->getValue();	
						if(!empty($excel_mobile)){
							if ((int)$this->validateMobileNumber($excel_mobile) === 0) {
							$err_column_array['error']["$excel_line_value$i"]    = $view_name;
								$msg_line = "[$cell_value] - Invalid... Please map The correct mobile number ";
							$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
							}
						}
					}elseif($field_type === 12){  	//FOR EMAIL		
						if($mandatory_field === 1){ //[MS 09-07-2024]
							$excel_email      = $sheet->getCell("$col_key$i")->getValue();
							$email 			  = $excel_email;
							if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
								$err_column_array['error']["$excel_line_value$i"]    = $view_name;
								$msg_line = "[$cell_value] - Invalid... Please map The correct Email";
								$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
							}				
						}else{
							$excel_email      = $sheet->getCell("$col_key$i")->getValue();
							$email 			  = $excel_email;
						}		
					}elseif($field_type === 13){  //FOR DATE & TIME  				
						$cell 			  = $sheet->getCell("$col_key$i");
						$excelDateValue   = $cell->getFormattedValue();
						$format           = $sheet->getCell("$col_key$i")->getStyle()->getNumberFormat()->getFormatCode();
						if(!empty($excelDateValue)){
							if ((int)$this->validateDateTime($excelDateValue) === 0) {
								$err_column_array['error']["$excel_line_value$i"]   = $view_name;
								$msg_line = "[$cell_value] - Invalid ... Please map the correct DATE & TIME format (DD-MM-YYYY HH:MM:SS)";
								$err_column_tabview['error']["$excel_line_value$i"] = $view_name." ".$msg_line;
							}
						}
					}elseif($field_type === 14){  	//READ ONLY
						$readonly       = $sheet->getCell("$col_key$i")->getValue(); 
						if ($readonly) {
							$err_column_array['error']["$excel_line_value$i"]    = $view_name;
							$msg_line   = "Field is read-only. Modifications are not allowed.";
							$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;    
						}
					}elseif($field_type === 15){   // FOR TIME  
						$cell 			= $sheet->getCell("$col_key$i");  	 
						$excelDateValue = $cell->getFormattedValue(); 
						$excelDateValue = preg_replace('/(\b\d{1}\b)/', '0$1', $excelDateValue);
						if(!empty($excelDateValue)){
							if ((int)$this->validatetime($excelDateValue) === 0) {
								$err_column_array['error']["$excel_line_value$i"]   = $view_name;
								$msg_line = "[$cell_value] - Invalid ... Please map the correct TIME format (HH:MM:SS)";
								$err_column_tabview['error']["$excel_line_value$i"] = $view_name." ".$msg_line;
							}
						}
					}elseif($field_type === 1){ //LENGTH VALIDATION
						if($text_type === 1 || $text_type === 2 || $text_type === 3){ 
							if(strlen($cell_value) > $field_length ){
								$err_column_array['error']["$excel_line_value$i"] = $view_name;
								$msg_line     = "Invalid - Please provide complete $field_length-digit $view_name to proceed.!";
								$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
							}		
							
						}
					}
					$i++;
				}
			}	
		}
		return $err_column_tabview;	
	}

	//PERFORMING CUSTOM INPUT VALIDATIONS -> STATIC
	public function validate_excel_import_static($sheet,$excel_obj,$import_type,$excel_format_result,$excel_row_start,$total_rows){
		$permission_qry       = 'SELECT role,count(*) AS permission_count FROM cw_employee_permission WHERE cw_employee_permission.trans_status = 1 group by role';
		$permission_info      = $this->db->query("CALL sp_a_run ('SELECT','$permission_qry')");
		$permission_rslt      = $permission_info->result_array();
		$permission_info->next_result();
		$permission_rslt      = array_reduce($permission_rslt, function ($result, $arr) {
			$result[$arr['role']] = $arr['permission_count'];
			return $result;
		}, array());
		$this->save_info();
		$company_info   	  = $this->company_info();
		$minimum_age 		  = $company_info[0]->minimum_age;
		$maximum_age 		  = $company_info[0]->maximum_age;	
		$msg_line 			  = "";
		$sts 				  = 1;

		//LEAVE STATUS 
		$leave_financial_info = $this->get_leave_financial_details();
		$prime_financial_id   = $leave_financial_info[0]->prime_leave_financial_year_id;
		$leave_status_query   = " SELECT employee_code FROM cw_request WHERE cw_request.leave_status = 1 AND cw_request.trans_status = 1	 AND financial_setting_id = '".$prime_financial_id."'";
		$leave_status_data    = $this->db->query($leave_status_query);
		$leave_status_result  = $leave_status_data->result_array();
		$leave_status_result  = array_reduce($leave_status_result, function ($result, $arr){
		    $result[$arr['employee_code']] = $arr;
		    return $result;
		}, array());

		//INCOME TAX 
		$finance_arr 		  = $this->get_financial_year();
		$finance_id 		  = $finance_arr[0]->prime_financial_setting_id;
		$income_tax_qry       = 'SELECT emp_code FROM cw_tax_calculation WHERE fin_set_id = "'.$finance_id.'"  and trans_status = 1';
		$income_tax_info      = $this->db->query($income_tax_qry);
		$income_tax_rslt   	  = $income_tax_info->result_array();
		$income_tax_rslt      = array_reduce($income_tax_rslt, function ($result, $arr){
		    $result[$arr['emp_code']] = $arr;
		    return $result;     
		}, array());

		//OVERTIME REQUEST
		$overtime_req_qry     = "SELECT employee_code FROM cw_overtime_request WHERE cw_overtime_request.approval_status = 1 AND cw_overtime_request.trans_status = 1 AND cw_overtime_request.financial_setting_id = '".$prime_financial_id."'";
		$overtime_req_data    = $this->db->query($overtime_req_qry);
		$overtime_req_result  = $overtime_req_data->result_array();
		$overtime_req_result  = array_reduce($overtime_req_result, function ($result, $arr){
		    $result[$arr['employee_code']] = $arr;
		    return $result;
		}, array());
    
		//STATIC VALIDATIONS START
		for($row = $excel_row_start; $row <= $total_rows; $row++){
			$employee_code    = "";	
			$label_name_arr   = array();
			foreach($excel_format_result as $excel_info){
				$field_type             = (int)$excel_info->field_type;
				$excel_line_column_name = $excel_info->excel_line_column_name;
				$excel_line_value       = $excel_info->excel_line_value;
				$view_name              = $excel_info->view_name;
				$pick_list_type         = (int)$excel_info->pick_list_type;
				$pick_list              = $excel_info->pick_list;
				$pick_table             = $excel_info->pick_table;
				$pick_list_import       = (int)$excel_info->pick_list_import;
				$mandatory_field        = (int)$excel_info->mandatory_field;
				$date_type              = (int)$excel_info->date_type;
				$field_length           = (int)$excel_info->field_length;
				$input_view_type        = (int)$excel_info->input_view_type;
				$get_cell_value         = trim($sheet->getCell("$excel_line_value$row")->getCalculatedValue());
				//CHANGING "",'',& TO ~,^,`
				if($get_cell_value){
					$get_cell_value     = str_replace('"',"~",$get_cell_value);
					$get_cell_value     = str_replace("'","`",$get_cell_value);
				}
				// LABEL NAME AND VIEW NAME ARRAY !
				$label_name_arr[$excel_line_column_name]  = $view_name;
				$post_data[$excel_line_column_name]       = $get_cell_value;
				if($excel_line_column_name === "employee_code"){
					$employee_code          = $get_cell_value;
				}
				//DATE
				if($date_type === 1){
					$format = $sheet->getCell("$excel_line_value$row")->getStyle()->getNumberFormat()->getFormatCode();
					if($format  === "General" || $format === "@"){
						$rawDateValue = $sheet->getCell("$excel_line_value$row")->getValue();
						$parsedDate   = DateTime::createFromFormat('d-m-Y', $rawDateValue);
						if($parsedDate){
							$get_date_value = $parsedDate->format('Y-m-d');
						}	
					}else
					if($format === "m/d/yyyy" || $format === "[$-14009]dd/mm/yyyy" || $format === "[$-F800]dddd\,\ mmmm\ dd\,\ yyyy" || $format === "[$-14009]dd/mm/yyyy;@"){
						$get_date_value = trim(Date::excelToDateTimeObject((int)$sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));
					}else{
						$get_date_value = '';
					}
				}
				//EXACT LENGTH VALIDATION !
				if($excel_line_column_name === "aadhar_card_no" || $excel_line_column_name === "mobile_number" ){
					if($mandatory_field === 1){//[MS 09-07-2024]
						if($field_length !== strlen($get_cell_value)){
							$err_column_array['error']["$excel_line_value$row"]    = $view_name;
							$msg_line = "Invalid $view_name. Please check.!";
							$err_column_tabview['error']["$excel_line_value$row"]  = $get_cell_value." - ".$msg_line;
						}
					}else{
						if($get_cell_value){
							if($field_length !== strlen($get_cell_value)){
								$err_column_array['error']["$excel_line_value$row"]    = $view_name;
								$msg_line = "Invalid $view_name. Please check.!";
								$err_column_tabview['error']["$excel_line_value$row"]  = $get_cell_value." - ".$msg_line;
							}
						}
					}
				}
				//ONLY NUMBERS ALLOWED!
				if( $excel_line_column_name === "bank_account_number" || $excel_line_column_name === "aadhar_card_no"){
					if($get_cell_value){
						if(!is_numeric($get_cell_value)){
							$err_column_array['error']["$excel_line_value$row"]    = $view_name;
							$msg_line = "Invalid $view_name. Please check.!";
							$err_column_tabview['error']["$excel_line_value$row"]  = $get_cell_value." - ".$msg_line;
						}
					}
				}
				//ENTRY AND EXIT TIME
				if($excel_line_column_name === 'entry_time' || $excel_line_column_name === 'exit_time'){
					$value      = $get_cell_value;
					$value      = explode(":", $value);					
					$hours      = (int)$value[0];
					$mins       = (int)substr("$value[1]",0,2);
					$meridiem   = substr("$value[1]",2,2);
					if(!(($hours >= 0 && $hours <= 12) && ($mins <= 60 && $mins >= 0) && ($meridiem === "AM" || $meridiem === "PM"))){
						if($excel_line_column_name === 'exit_time'){
							$err_column_array['error']["$excel_line_value$row"]    = $view_name;
							$msg_line = "[$get_cell_value] - Invalid... Please map The Date Format Like (06:30AM)";
							$err_column_tabview['error']["$excel_line_value$row"]  = $view_name." ".$msg_line; 
						}else{
							$err_column_array['error']["$excel_line_value$i"]    = $view_name;
							$msg_line = "[$get_cell_value] - Invalid... Please map The Date Format Like (09:30AM)";
							$err_column_tabview['error']["$excel_line_value$row"]  = $view_name." ".$msg_line;
						}
					}
				} 
				//FIRST AND SECOND LEVEL APPROVAL
				if($excel_line_column_name === "first_level_approval" || $excel_line_column_name === "second_level_approval" || $excel_line_column_name === "approve_type"){
					if($leave_status_result[$employee_code]){
						$err_column_array['error']["$excel_line_value$row"]    = $view_name;
						$msg_line = "Don't Change because our Request Status was Pending??";
						$err_column_tabview['error']["$excel_line_value$row"]  = $view_name." ".$msg_line;
					}else
					if($overtime_req_result[$employee_code]){
						$err_column_array['error']["$excel_line_value$row"]    = $view_name;
						$msg_line = "Don't Change because our OT Request Status was Pending??";
						$err_column_tabview['error']["$excel_line_value$row"]  = $view_name." ".$msg_line;
					}
				}
				//INCOME TAX VALIDATION.
				if($excel_line_column_name === "income_tax_type"){
					if($income_tax_rslt[$employee_code]){
						$err_column_array['error']["$excel_line_value$row"]    = $view_name;
						$msg_line = "Invalid - Income Tax Already processed for this financial year";
						$err_column_tabview['error']["$excel_line_value$row"]  = $view_name." ".$msg_line;
					}
				}
				//PAN CARD VALIDATION 
				if($excel_line_column_name === "pan_number"){
					if($mandatory_field === 1){//[MS 09-07-2024]
						if((int)$this->validatePanCard($get_cell_value) === 0){
							$err_column_array['error']["$excel_line_value$row"]    = $view_name;
							$msg_line = "Invalid Pan Card format. Please check.";
							$err_column_tabview['error']["$excel_line_value$row"]  = $get_cell_value." - ".$msg_line;
						}
					}else{
						if($get_cell_value){
							if((int)$this->validatePanCard($get_cell_value) === 0){
								$err_column_array['error']["$excel_line_value$row"]    = $view_name;
								$msg_line = "Invalid Pan Card format. Please check.";
								$err_column_tabview['error']["$excel_line_value$row"]  = $get_cell_value." - ".$msg_line;
							}
						}
					}
				}
				//DATE OF BIRTH
				if($excel_line_column_name === "date_of_birth"){
					$dob_date_value 		= $get_date_value;
					if(!empty($dob_date_value)){
						if((strpos($dob_date_value,"'") || strpos($dob_date_value,'"')) !== false){
							$dob_date_value = str_replace("'", "", $dob_date_value);
							$dob_date_value = date('Y-m-d', strtotime($dob_date_value));
						}
						$str_dob = null;
						if($dob_date_value){
							$str_dob        = strtotime($dob_date_value);
						}
						if((int)$minimum_age > 0){
							$sminimum_age   = "+$minimum_age";
						}
						if((int)$maximum_age > 0){
							$smaximum_age   = "+$maximum_age";
						}
						$date_diff_val      = date( "Y-m-d", strtotime( "$dob_date_value $sminimum_age years" ));//after 14 years add
						$date_diff_val      = strtotime($date_diff_val);
						$date_max_val       = date( "Y-m-d", strtotime( "$dob_date_value $smaximum_age years" ));//after 14 years add
						$date_max_val       = strtotime($date_max_val);
						$dob_line_val       = $excel_info->excel_line_value;
						$dob_view_name      = $view_name;
					}
				}
				//DATE OF JOINING 
				$str_doj = null;
				if($excel_line_column_name === "date_of_joining"){
					$doj_date_value     	= $get_date_value;
					if($doj_date_value){
						$str_doj 		    = strtotime($doj_date_value);
					}
				}	
				//MINIMUM AND MAXIMUM AGE VALIDATION
				$today     	  = date('Y-m-d');
				$str_today    = strtotime($today);
				if((int)$minimum_age === 0 || (int)$maximum_age === 0){
					$err_column_array['error']["min_max_age$row"]    = "minimum_age";
					$msg_line = "Please set minimum age & maximum age";
					$err_column_tabview['error']["min_max_age$row"]  = "min max age"." ". $msg_line;
				}
				if($str_dob && $str_doj){
					if((int)$str_dob > (int)$str_doj){
						$err_column_array['error']["$dob_line_val$row"]    = $dob_view_name;
						$msg_line = " should not be greater than the date of joining.";
						$err_column_tabview['error']["$dob_line_val$row"]  = $dob_view_name." ".$msg_line; 
					}else
					if((int)$date_diff_val > (int)$str_doj){
						$err_column_array['error']["$dob_line_val$row"]    = $dob_view_name;
						$msg_line = " minimum difference for date of birth is $minimum_age years, please change the date?";
						$err_column_tabview['error']["$dob_line_val$row"]  = $dob_view_name." ". $msg_line; 
					}else
					if((int)$date_max_val < (int)$str_doj){
						$err_column_array['error']["$dob_line_val$row"]    = $dob_view_name;
						$msg_line = " minimum difference for date of birth is $maximum_age years, please change the date?";
						$err_column_tabview['error']["$dob_line_val$row"]  = $dob_view_name." ". $msg_line; 
					}
				}
				$str_resign         = null;
    			$str_last_work_date = null;
				//RESIGNATION DATE
				if($excel_line_column_name === "resignation_date"){
					$resign_date_value		= $get_date_value;
					if($resign_date_value){
						$str_resign         = strtotime($resign_date_value);
						$resign_line_val    = $excel_info->excel_line_value;
						$resign_view_name   = $view_name;
					}
				}
				//LAST WORKING DATE
				if($excel_line_column_name === "last_working_date"){
					$last_work_date_value 	= $get_date_value;
					if($last_work_date_value){
						$str_last_work_date     = strtotime($last_work_date_value);
						$last_work_date_val     = $excel_info->excel_line_value;
						$last_work_view_name    = $view_name;
					}
				}
				//RESIGNATION DATE 
				if($str_resign !== null && $str_last_work_date !== null){
					if((int)$str_resign > (int)$str_last_work_date){ 
						$err_column_array['error']["$last_work_date_val$row"] = $last_work_view_name;
						$msg_line = " should not be greater than Resignation date, please change the date?";
						$err_column_tabview['error']["$last_work_date_val$row"]  = $last_work_view_name." ".$msg_line;
					}
				}
				//USER RIGHT 
				if($excel_line_column_name === "user_right"){
					if($pick_list_type     === 1){
						$pick_list_val      = explode(",",$pick_list);
						$pick_list_val_1    = $pick_list_val[0];
						$pick_list_val_2    = $pick_list_val[1];
					}else
					if($pick_list_type     === 2){
						$pick_list_val_1    = $pick_table."_id";
						$pick_list_val_2    = $pick_table."_value";
						$pick_list_val_3    = $pick_table."_status";
					}
					if($pick_list_import   === 1){
						$pick_query         = 'select '.$pick_list_val_1.' from '.$pick_table.' where '.$pick_list_val_1.' = "'.$get_cell_value.'"';
					}else{
						$pick_query         = 'select '.$pick_list_val_1.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
					}				
					$pick_data              = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
					$pick_result            = $pick_data->result();
					$pick_data->next_result();
					$permission_role_id     = $pick_result[0]->$pick_list_val_1;
					$permission_count       = $permission_rslt[$permission_role_id];
					if((int)$permission_count === 0){
						$err_column_array['error']["$excel_line_value$row"] = $view_name;
						$msg_line = "Invalid[$get_cell_value] - Employee permission required for this role.";
						$err_column_tabview['error']["$excel_line_value$row"]  = $get_cell_value." - ".$msg_line; 
					}
				}
			}
			//UNIQUE VALIDATION PROCEDURE	
			if($post_data){
				$post_json_data     	= json_encode($post_data);		
				$error_sts_arr          = $this->unique_procedure_valid($post_json_data);
				if(count($error_sts_arr ?? [])){
					if($error_sts_arr[0] !== 1){
						$err_code       = $error_sts_arr[0]['employee_code'];
						$err_field      = $error_sts_arr[0]['field_name'];
						$err_value      = $error_sts_arr[0]['field_value'];
						$err_msg        = $error_sts_arr[0]['error_message'];
						$err_column_array['error']["$row"]    = $row;
						$err_view_name  = $label_name_arr[$err_field];
						$err_column_tabview['error']["$row"]  = "Duplicate entry: $err_value already exists in $err_view_name for Employee Code: $err_code.";
					}
				}
			}
		}
		// die;
		$check_array = array("err_column_array"=>$err_column_array,"err_column_tabview"=>$err_column_tabview);
		return $check_array;
	}

	public function emp_final_excel_import($module_id,$sheet,$import_type,$excel_format_result,$excel_row_start,$total_rows,$exist_column_name){
		$status_array	                = array();
		$formula_process         	    = array();
		$emp_log                        = array();
		for($row = $excel_row_start; $row <= $total_rows; $row++){
			$prime_upd_query 		 	= "";
			$prime_column_val 		 	= "";
			$prime_cell_val   		 	= "";
			$exist_val        		 	= "";
			$status_info     		 	= array();
			$status_info["Excel Row"]	= $row;
			$sts 					 	= 1;
			foreach($excel_format_result as $excel_info){
				$field_isdefault        = (int)$excel_info->field_isdefault;
				$mandatory_field        = (int)$excel_info->mandatory_field;
				$field_type             = (int)$excel_info->field_type;
				$view_name              = $excel_info->view_name;
				$pick_table             = $excel_info->pick_table;
				$pick_list_type         = (int)$excel_info->pick_list_type;
				$pick_list_import       = (int)$excel_info->pick_list_import;
				$pick_list              = $excel_info->pick_list;
				$excel_line_column_name = $excel_info->excel_line_column_name;
				$excel_line_value       = $excel_info->excel_line_value;
				$input_view_type        = $excel_info->input_view_type;
				$date_type              = (int)$excel_info->date_type;
				$unique_field 			= (int)$excel_info->unique_field;
				$get_cell_value         = trim(mb_convert_encoding($sheet->getCell("$excel_line_value$row")->getCalculatedValue(), "ISO-8859-1", "UTF-8"), " \t\n\r\0\x0B\xA0");
				//CHANGING "",'',& TO ~,^,`
				if($get_cell_value){
					$get_cell_value     = str_replace('"',"~",$get_cell_value);
					$get_cell_value     = str_replace("'","`",$get_cell_value);
				}
				//EMPLOYEE CODE 
				if($excel_line_column_name === "employee_code"){
					$get_cell_value     = trim($get_cell_value);
					$user_name 			= $get_cell_value;
					$code     		    = $get_cell_value;
					// NEW ENCRYPT PASSWORD METHOD ADDED _ARN 04-11-2025
					$password           = $this->Module->cryptoEncrypt(md5($get_cell_value)); 
				}
				//DATE 
				if($field_type === 4){							
					if($date_type   === 1){  //FOR DATE-MONTH-YEAR
						$format = $sheet->getCell("$excel_line_value$row")->getStyle()->getNumberFormat()->getFormatCode();
						if($format  === "General" || $format === "@"){
							$rawDateValue   = $sheet->getCell("$excel_line_value$row")->getValue();
							$parsedDate     = DateTime::createFromFormat('d-m-Y', $rawDateValue);
							if($parsedDate){
								$get_cell_value = $parsedDate->format('Y-m-d');
							}	
						}else
						if($format === "m/d/yyyy" || $format === "[$-14009]dd/mm/yyyy" || $format === "[$-F800]dddd\,\ mmmm\ dd\,\ yyyy" || $format === "[$-14009]dd/mm/yyyy;@"){
							$get_cell_value = trim(Date::excelToDateTimeObject((int)$sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));	
						}
					}else
					if($date_type === 2){  //FOR MONTH-YEAR
						$cell             = $sheet->getCell("$excel_line_value$row");
						$get_cell_value   = $cell->getFormattedValue();
					}else
					if($date_type === 3){  //FOR YEAR
						$cell 			= $sheet->getCell("$excel_line_value$row");
						$get_cell_value = $cell->getFormattedValue();
					}else{
						$get_cell_value = '';
    				}
				}
				// FOR PICKLIST CHECK
				if(($field_type === 5) || ($field_type === 7) || ($field_type === 9)){
					if(($get_cell_value !== '') || ($get_cell_value !==0) || ($get_cell_value !== null)){ 
						if($pick_list_type  === 1){   //FROM TABLE
							$pick_list_val   = explode(",",$pick_list);
							$pick_list_val_1 = $pick_list_val[0];
							$pick_list_val_2 = $pick_list_val[1];
							if($field_type === 7){ //IF THEY WAS MULTI PICKLIST _ARN
								$values    = array_map('trim', explode(',', $get_cell_value));
								$final_ids = [];

								foreach($values as $val){
									if($pick_list_import === 1){
										$pick_query = 'SELECT '.$pick_list.' FROM '.$pick_table.' WHERE '.$pick_list_val_1.' = "'.$val.'"';
									}else{
										$pick_query = 'SELECT '.$pick_list.' FROM '.$pick_table.' WHERE '.$pick_list_val_2.' = "'.$val.'"';
									}

									$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
									$pick_result = $pick_data->result();
									$pick_count  = $pick_data->num_rows();
									$pick_data->next_result();
									if((int)$sts != 0){
										if((int)$pick_count === 0){
											// INSERT
											if($pick_table !== $this->prime_table){
												$ins_query = 'INSERT INTO '.$pick_table.'('.$pick_list_val_2.') VALUES ("'.$val.'")';
												$ins_info   = $this->db->query("CALL sp_a_run ('INSERT','$ins_query')");
												$ins_result = $ins_info->result();
												$ins_info->next_result();
												$final_ids[] = $ins_result[0]->ins_id;
											}
										}else{
											// UPDATE IF INACTIVE
											$pick_id     = $pick_result[0]->$pick_list_val_1;
											$pick_status = (int)$pick_result[0]->trans_status;
											if($pick_status === 0){
												$upd_query = 'UPDATE '.$pick_table.' SET trans_status = 1 WHERE '.$pick_list_val_1.' = '.$pick_id;
												$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
											}
											$final_ids[] = $pick_id;
										}
									}
								}
								// FINAL VALUE STORED IN EMPLOYEE
								$get_cell_value = implode(',', $final_ids);
							}else{
								if($pick_list_import === 1){
									$pick_query  = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_1.' = "'.$get_cell_value.'"';
								}else{
									$pick_query  = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
								}
								$pick_data       = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
								$pick_result     = $pick_data->result();
								$pick_count      = $pick_data->num_rows();
								$pick_data->next_result();
								$created_on      = date("Y-m-d H:i:s");
								if((int)$sts != 0){
									if((int)$pick_count === 0){
										if($get_cell_value){
											// $pick_list_val_2      .= ",trans_created_by,trans_created_date";
											$get_cell_value_val    = '"'.$get_cell_value.'"';
											// $get_cell_value_val   .= '"'.$this->logged_id.'",'.'"'.$created_on.'"';
											if($pick_table !== $this->prime_table){
												$ins_query         = 'insert into '.$pick_table.'('.$pick_list_val_2.') VALUES ('.$get_cell_value_val.')';
												$ins_info          = $this->db->query("CALL sp_a_run ('INSERT','$ins_query')");
												$ins_result        = $ins_info->result();
												$ins_info->next_result();
												$get_cell_value    = $ins_result[0]->ins_id;
												$second_insert_id  = $ins_result[0]->ins_id;
												$prime_id          = $pick_table."_id";
												$prime_id          = str_replace("cw_","prime_",$prime_id);
											}
										}
									}else
									if((int)$pick_count > 0){
										if($pick_table !== $this->prime_table){
											$pick_id           = $pick_result[0]->$pick_list_val_1;
											$pick_status       = (int)$pick_result[0]->trans_status;
											if($pick_status   === 0){
												$upd_query     = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = '.$pick_id;
												$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
											}
											$get_cell_value    = $pick_id;
										}
									}
								}
							}
						}else
						if($pick_list_type === 2){  //New picklist list
							$pick_list_val_1 = $pick_table."_id";
							$pick_list_val_2 = $pick_table."_value";
							$pick_list_val_3 = $pick_table."_status";
							if($field_type === 7){ //IF THEY WAS MULTIPICKLIST _ARN
								$values    = array_filter(array_map('trim', explode(',', $get_cell_value)));
								$final_ids = [];
								foreach($values as $val){
									$pick_query = 'SELECT * FROM '.$pick_table.' WHERE '.$pick_list_val_2.' = "'.$val.'"';
									$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
									$pick_result = $pick_data->result();
									$pick_count  = $pick_data->num_rows();
									$pick_data->next_result();
									if((int)$pick_count === 0){
										if($pick_table !== $this->prime_table){
											$ins_query = 'INSERT INTO '.$pick_table.'('.$pick_list_val_2.') VALUES ("'.$val.'")';
											$ins_info   = $this->db->query("CALL sp_a_run ('INSERT','$ins_query')");
											$ins_result = $ins_info->result();
											$ins_info->next_result();
											$final_ids[] = $ins_result[0]->ins_id;
											
										}
									}else{
										$pick_id     = $pick_result[0]->$pick_list_val_1;
										$pick_status = (int)$pick_result[0]->$pick_list_val_3;
										if($pick_status === 0){
											$upd_query = 'UPDATE '.$pick_table.' SET '.$pick_list_val_3.' = 1 WHERE '.$pick_list_val_1.' = '.$pick_id;
											$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
										}
										$final_ids[] = $pick_id;
									}
								}
								$get_cell_value = implode(',', $final_ids);

							}else{
								$pick_query      = 'select * from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
								$pick_data       = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
								$pick_result     = $pick_data->result();
								$pick_count      = $pick_data->num_rows();
								$pick_data->next_result();
								if((int)$pick_count === 0){
									if($pick_table !== $this->prime_table){
										$ins_query        = 'insert into '.$pick_table.'('.$pick_list_val_2.') VALUES ("'.$get_cell_value.'")';
										$ins_info         = $this->db->query("CALL sp_a_run ('INSERT','$ins_query')");
										$ins_result       = $ins_info->result();
										$ins_info->next_result();
										$get_cell_value   = $ins_result[0]->ins_id;
										$second_insert_id = $ins_result[0]->ins_id;
										$prime_id = $pick_table."_id";
										$prime_id = str_replace("cw_","prime_",$prime_id);
									}
								}else
								if((int)$pick_count === 1){
									if($pick_table !== $this->prime_table){
										$pick_id         = $pick_result[0]->$pick_list_val_1;
										$pick_status     = (int)$pick_result[0]->$pick_list_val_3;
										if($pick_status === 0){
											$upd_query   = 'update '.$pick_table.' set '.$pick_list_val_3.' = 1 where '.$pick_list_val_1.' = '.$pick_id;
											$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
										}
										$get_cell_value  = $pick_id;
									}
								} 
							}
						}
					}
				}
				if($field_isdefault === 1){
					//CHANGING '' TO ^
					$get_cell_value          = str_replace("'",'^', $get_cell_value);
					$prime_column_val       .= $excel_line_column_name . ",";
					$prime_cell_val         .= "\'" . $get_cell_value . "\',";
					// EMPLOYEE LOG TABLE INSERT ON IMPORT TIME _ARN
					$emp_log[$excel_line_column_name] = $get_cell_value;
					if(empty($exist_column_name)){
						if($mandatory_field === 1){
							$exist_val.= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
						}
						$update_cell_val     = '"'.$get_cell_value.'",';
						$prime_upd_query    .= $excel_line_column_name."=".$update_cell_val;
					}else{
						if(in_array($excel_line_column_name,$exist_column_name)){
							$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
						}
						$update_column_val   = $excel_line_column_name;
						$update_cell_val     = '"'.$get_cell_value.'",';
						$prime_upd_query    .= $update_column_val."=".$update_cell_val;
					}


					//RESIGNATION DATE || LAST WORKING DATE 
					if($excel_line_column_name === "resignation_date" || $excel_line_column_name === "last_working_date"){
						$resignation_date 	 = $get_cell_value;
						$last_working_date   = $get_cell_value;
   						if(!empty($resignation_date) || !empty($last_working_date)){
   						    $prime_upd_query .= 'termination_status = "1", ';
   						}elseif (empty($resignation_date) && empty($last_working_date)){
   						    $prime_upd_query .= 'termination_status = "0", ';
   						}
					}
					//DOJ
					if($excel_line_column_name === "date_of_joining"){
						$doj 				 =  $get_cell_value;
					}
					//EMP NAME
					if($excel_line_column_name === "emp_name"){
						$empname 			 = $get_cell_value;
					}
					//GENDER
					if($excel_line_column_name === "gender"){
						$gender 			 = $get_cell_value;
						if((int)$gender === 2){
							$gender 		 = "F";
						}else{
							$gender 		 = "M";
						}
					}
					//DOB
					if($excel_line_column_name === "date_of_birth"){
						$dob 				 = $get_cell_value;
					}
					//MARITAL STATUS
					if($excel_line_column_name === "marital_status"){
						$marital_status 	 = $get_cell_value;
						if((int)$marital_status === 1){
							$marital_status  = "Married";
						}else{
							$marital_status  = "UnMarried";
						}
					}
					//ROLE
					if($excel_line_column_name === "role"){
						$role 				 = $get_cell_value;
					}
					//USER RIGHT
					if($excel_line_column_name === "user_right"){
						$user_right  		 = (int)$get_cell_value;
					}
				}
				if((int)$import_type === 3){
					$rowset_column_val      .= $excel_line_column_name.",";
					$rowset_cell_val        .= '"'.$get_cell_value.'",';
					if($excel_line_column_name === "employee_code"){
						$emp_code_qry        = 'select prime_employees_id from cw_employees where trans_status =1 and employee_code = "'.$get_cell_value.'"';
						$emp_data            = $this->db->query("CALL sp_a_run ('SELECT','$emp_code_qry')");
						$emp_data_result     = $emp_data->result();
						$emp_data->next_result();
						$emp_id              = $emp_data_result[0]->prime_employees_id;
						$rowset_column_val   = "prime_employees_id,";
						$rowset_cell_val     ='"'.$emp_id.'",';
					}
				}
			}
			// ============== FILTER KEY AND ENTITY SET AUDIT LOG _ARN 10-02-2026 ==============
			$filter_keys   = ["User Right" => $user_right ,"Employee Code" => $code];
			if((int)$sts !== 0){
				$created_on  = date("Y-m-d h:i:s");
				if((int)$import_type === 3){
					$rowset_column_val 		      .= "trans_created_by,trans_created_date";
					$rowset_cell_val   		      .= '"'.$this->logged_id.'",'.'"'.$created_on.'"';
					$rowset_column_val 		       = rtrim($rowset_column_val,",");
					$rowset_cell_val   		       = rtrim($rowset_cell_val,",");
					$table_name        		       = $table_name_list[2];
					$rowset_query      		       = "insert into $table_name ($rowset_column_val) VALUES ($rowset_cell_val)";
					$rowset_insert_info            = $this->db->query("CALL sp_a_run ('INSERT','$rowset_query')");
					$rowset_insert_result          = $rowset_insert_info->result();
					$rowset_insert_info->next_result();
					$insert_id 				       = $rowset_insert_result[0]->ins_id;
					$status_info['Status']         = "Inserted to DB";
				}else{
					if($prime_column_val){
						$prime_id    		       = "prime_".$module_id."_id";
						$exist_val                 = rtrim($exist_val," and ");
						$exist_query               = "select count(*) exist_count,trans_status,$prime_id from $this->prime_table where $exist_val";
						$exist_info                = $this->db->query("CALL sp_a_run ('RUN','$exist_query')");
						$exist_result              = $exist_info->result();
						$exist_info->next_result();
						$exist_count               = $exist_result[0]->exist_count;
						//GET GRANTS VALUES LIST
						$emp_perm_grants_ary       = array();
						if($user_right){
							$emp_per_qry           = 'select * from cw_employee_permission where cw_employee_permission.trans_status =1 and cw_employee_permission.role = "'.$user_right.'"';
							$emp_per_data 	       = $this->db->query("CALL sp_a_run ('SELECT','$emp_per_qry')");
							$emp_per_rslt          = $emp_per_data->result_array();
							$emp_per_data->next_result();

							$emp_perm_grants_ary   = array_reduce($emp_per_rslt, function ($result, $arr){
								$result[$arr['role']][] = $arr;
								return $result;
							}, array());
						}
						if((int)$import_type === 1){
							if((int)$exist_count === 0){
								$prime_column_val .= "user_name,password,trans_created_by,trans_created_date";
								$prime_cell_val   .= '"'.$user_name.'","'.$password.'","'.$this->logged_id.'",'.'"'.$created_on.'"';
								$prime_column_val  = rtrim($prime_column_val,",");
								$prime_cell_val    = rtrim($prime_cell_val,",");
								// EMPLOYEE LOG INSERT CALL _ARN 31-01-2026
								$this->employee_log(0,$emp_log);
								$prime_query       = "insert into $this->prime_table ($prime_column_val) VALUES ($prime_cell_val)";
								$insert_info       = $this->db->query("CALL sp_a_run ('INSERT','$prime_query')");
								$insert_result     = $insert_info->result();
								$insert_info->next_result();
								$insert_id 		   = $insert_result[0]->ins_id;
								$code_info         = $this->db->query("CALL sp_a_run ('SELECT','SELECT employee_code FROM `cw_employees` where prime_employees_id = ".$insert_id." and trans_status = 1')");
								$code_result       = $code_info->result();
								$code_info->next_result();
								$employee_code     = $code_result[0]->employee_code;
								$formula_process[] = $employee_code;
								$status_info['Status'] = "Inserted to DB";
								if((int)$insert_id){
									$update_grants_sts = $this->update_grants($insert_id,$emp_perm_grants_ary,$filter_keys);
									$emp_data          = array("Compcode"=>"C0001","CODE"=>$code,"EMPNAME"=>$empname,"DEPT"=>$department,"DESIG"=>$designation,"DOJ"=>$doj,"DOB"=>$dob,"MARTIAL"=>$marital_status,"SEX"=>$gender,"cCode"=>$role);
									$imp_sts = False;
								}	
							}else{
								$imp_sts = True;
								$imp_msg = "Employee Code Already Exists..";
							}
						}else{
							if((int)$exist_count === 1){
								$upd_prime_id        = (int)$exist_result[0]->$prime_id;
								// EMPLOYEE LOG INSERT CALL _ARN 31-01-2026
								$this->employee_log($upd_prime_id,$emp_log);
								$prime_update_query  = 'UPDATE '. $this->prime_table .' SET '. $prime_upd_query .' trans_updated_by = "'.$this->logged_id.'",trans_updated_date = "'.$created_on.'" WHERE '. $prime_id .' = "'. $upd_prime_id .'"';
								$upd_rslt            = $this->db->query($prime_update_query);
								if($upd_rslt){
									//EMPLOYEEE PERMISSION GRANTS INSERT FUNCTION
									if(!empty($emp_perm_grants_ary)){
										$update_grants_sts = $this->update_grants($upd_prime_id,$emp_perm_grants_ary,$filter_keys);
									}
									$status_info['Status'] = "Updated to DB";
								}else{
									$status_info['Status'] = "Not Updated.. Try After Sometime..";
								}
								
								$code_info         = $this->db->query("CALL sp_a_run ('SELECT','SELECT employee_code FROM `cw_employees` where prime_employees_id = ".$upd_prime_id." and trans_status = 1')");
								$code_result       = $code_info->result();
								$code_info->next_result();
								$employee_code     = $code_result[0]->employee_code;
								$formula_process[] = $employee_code;
							}else{
								$emp_code_qry      = 'select prime_employees_id from cw_employees where trans_status =1 and employee_code = "'.$code.'"';
								$emp_data          =  $this->db->query("CALL sp_a_run ('SELECT','$emp_code_qry')");
								$emp_data_result   = $emp_data->result();
								$emp_data->next_result();
								$emp_id            = (int)$emp_data_result[0]->prime_employees_id;
								if($emp_id === 0){
									$status_info['Status'] = "Invalid Employee Code? Please Check it..!";
								}else{
									$imp_sts = True;
								}
							}
						}
					}
				}
				$status_array[] = $status_info;
			}
		}
		if($imp_sts){
			$table_info  = "";
			$status      = False;
			$msg         = "Invalid Excel Format to Import";
			if($imp_msg){
				$msg     = $imp_msg;
			}
		}else if ($status_array){
			$status      = True;
			$msg         = "Successfully files imported in database!!!";
			$table_info  = $this->get_excel_import_ui($status_array);
		}else{
			$status     = false;
			$msg        = "Files Not imported!!!";
		}
		$result  		 = $this->get_trans_array($formula_process);
		$emp_rslt		 = $this->Formula_model->import_formula($result);
		if($emp_rslt){
			foreach($emp_rslt as $emp_code => $final_trans){
				$import_update            = "";
				foreach($final_trans as $col_key => $col_value){
					$column_name          = $col_key;
					if(($column_name !== "$prime_id") && ($column_name !== "user_name")){
						if(($column_name == "confirmation_date") || ($column_name == "retirement_date") || ($column_name == "year_of_exp")) {
							$column_value =  date('Y-m-d',strtotime($col_value));
						}else{
							$column_value = $col_value;
						}
						$import_update   .= $column_name.' = "'.$column_value.'",';
					}	
				}
				$import_update       = rtrim($import_update,",");
				$import_update_query = 'UPDATE '.$this->prime_table.' SET '.$import_update.' WHERE employee_code= "'.$emp_code.'"';
				$this->db->query("CALL sp_a_run ('UPDATE','$import_update_query')");
			}
		}
		echo json_encode(array('success'=>$status,'message'=>$msg,'table_info'=>$table_info));
	}

	//IMPORT OFFLINE TDS ENTRY
	public function do_excel_offline_tds_import($import_id){
		$filename = dirname(__FILE__)."/php_excel/PHPExcel/IOFactory.php"; 
		include($filename);
		if($import_id < 0){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}
		$excel_path_qry             = 'SELECT * FROM cw_import WHERE import_id = "'.$import_id.'"';
		$excel_path_info            = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
		$excel_path_result          = $excel_path_info->result();
		$excel_path_info->next_result();
		if(!$excel_path_result){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}else{
			$excel_file_path        = $excel_path_result[0]->excel_file_path;
			$module_id              = $excel_path_result[0]->module_id;
			$import_type            = (int)$excel_path_result[0]->import_type;
			$excel_format           = $excel_path_result[0]->excel_format;
			$excel_sheet_name       = (int)$excel_path_result[0]->excel_sheet_name;
			$excel_row_start        = (int)$excel_path_result[0]->excel_start_row;
			$excel_row_end          = (int)$excel_path_result[0]->excel_end_row;
			$format_qry 	        = 'SELECT * FROM cw_util_excel_format WHERE prime_excel_format_id = "'.$excel_format.'" AND cw_util_excel_format.trans_status = 1';
			$format_info            = $this->db->query("CALL sp_a_run ('SELECT','$format_qry')");
			$format_rslt            = $format_info->result();
			$format_info->next_result();
			if(!$format_rslt){
				return json_encode(array('success' => false, 'message' => "Please add excel format before import"));
			}else{
				$exist_column_name 	= explode(",",$format_rslt[0]->exist_column_name);
				$excel_format_qry 	= 'SELECT IFNULL(pick_list_import,0) AS pick_list_import,input_view_type,field_length,label_name,unique_field,view_name,duplicate_data,field_length,picklist_data,field_type,date_type,text_type,pick_table,pick_list_type,pick_list,mandatory_field,field_isdefault,excel_line_column_name,excel_line_value FROM cw_util_excel_format_line INNER JOIN cw_form_setting ON label_name = excel_line_column_name WHERE excel_line_module_id = "'.$module_id.'" AND prime_excel_format_id = "'.$excel_format.'" AND cw_form_setting.prime_module_id = "'.$module_id.'" AND cw_util_excel_format_line.trans_status = 1';		
				$excel_format         = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
				$excel_format_result  = $excel_format->result();
				$excel_format->next_result();
				if(!$excel_format_result){
					return json_encode(array('success' => false, 'message' => "Please map excel cell column before import"));
				}else{
					try{
						$excel_obj    = \PhpOffice\PhpSpreadsheet\IOFactory::load($excel_file_path);
					}catch(Exception $e){
						die('Error loading file "' . pathinfo($excel_file_path, PATHINFO_BASENAME). '": ' . $e->getMessage());
						return json_encode(array('success' => false, 'message' => "Invalid file or path"));
					}
					$sheet 			  = $excel_obj->getSheet($excel_sheet_name);
					if($excel_row_end){
						$total_rows   = $excel_row_end;
					}else{
						$total_rows   = $sheet->getHighestRow();
					}
					$highest_column   = $sheet->getHighestColumn();
					foreach($excel_format_result as $excel_info){   
						$field_isdefault         = (int)$excel_info->field_isdefault;
						$mandatory_field         = (int)$excel_info->mandatory_field;
						$field_type              = (int)$excel_info->field_type;
						$excel_line_column_name  = $excel_info->excel_line_column_name;
						$excel_line_value        = $excel_info->excel_line_value;
						$view_name               = $excel_info->view_name;
						$pick_table              = $excel_info->pick_table;
						$pick_list_type          = (int)$excel_info->pick_list_type;
						$pick_list               = $excel_info->pick_list;
						$picklist_data           = (int)$excel_info->picklist_data;
						$pick_list_import        = (int)$excel_info->pick_list_import;
						$text_type       		 = (int)$excel_info->text_type;
						$date_type       		 = (int)$excel_info->date_type;
						$duplicate_data          = (int)$excel_info->duplicate_data;
						$field_length            = (int)$excel_info->field_length;
						$input_view_type         = (int)$excel_info->input_view_type;
						$common_multi_cell_value = $sheet->rangeToArray("$excel_line_value$excel_row_start:$excel_line_value$total_rows", NULL, TRUE, TRUE, TRUE);  
						$i = $excel_row_start;	
						foreach($common_multi_cell_value as $common_value){ 
							foreach($common_value as $col_key =>$cell_value){
								//FIELD TYPE VALIDATION STARTS !
								if(empty($cell_value) && $mandatory_field === 1){
									$err_column_array['error']["$excel_line_value$i"]    = $view_name;
									$msg_line      = " - Columns are required and they are empty. Please check.!";
									$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
								}elseif($excel_line_column_name === "employee_code" && $import_type === 2){ 
									$employee_code = $cell_value;   //FOR RESIGNED AND INACTIVE
									if(!isset($emp_code_data_result[$cell_value])){
										$err_column_array['error']["$excel_line_value$i"]    = $view_name;
										$msg_line  = "[$cell_value] Not found in employee master. Please check.";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}elseif($db_name !== "rad_hrms_db"){
										if($emp_code_data_result[$cell_value] === "1"){
											$err_column_array['error']["$excel_line_value$i"]    = $view_name;
											$msg_line  = "[$cell_value] Already resigned. Please check.!";
											$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
										}
									}
								}elseif($field_type === 4){		
									if($date_type === 2){  //FOR MONTH-YEAR
										$cell             = $sheet->getCell("$col_key$i");
										$excelDateValue   = $cell->getFormattedValue();
										if(!empty($excelDateValue)){
											if ((int)$this->validateMonthYear($excelDateValue) === 0){
												$err_column_array['error']["$excel_line_value$i"]   = $view_name;
												$msg_line = "[$cell_value] - Invalid ... Please map the correct MONTH-YEAR format (MM-YYYY)";
												$err_column_tabview['error']["$excel_line_value$i"] = $view_name." ".$msg_line;
											}
										}
									}
								}elseif($field_type === 5 || $field_type === 7){  //FOR PICKLIST
									//MANDATORY FIELDS
									if(($mandatory_field === 1) || ($picklist_data === 1)){  
										if($pick_list_type === 1){ //from table 
											$pick_list_val   = explode(",",$pick_list);
											$pick_list_val_1 = $pick_list_val[0];
											$pick_list_val_2 = $pick_list_val[1];
											$pick_list_where = $pick_list_val_2.' = "'.$cell_value.'"';
											if($pick_list_import === 1){
												$pick_list_where  = $pick_list_val_1.' = "'.$cell_value.'"';
											}
											//Checking if the value is present in the select table.
											$pick_query  = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_where;	
											$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
											$pick_result = $pick_data->result();
											$pick_count  = $pick_data->num_rows();
											$pick_data->next_result();
											if((int)$pick_count === 0){
												$err_column_array['error']["$excel_line_value$i"] = $view_name;
												$msg_line    = "- Invalid data[$cell_value] is present... Please check and try again.!";
												$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
											}
										} 
									} 
								}
								$i++;
							}
						}	
					}
					$err_column_count = count($err_column_array['error'] ?? []);
					if((int)$err_column_count > 0){
						$table_info = $this->get_excel_error_ui($err_column_tabview);
						echo json_encode(array('success'=>True,'message'=>"Column Wise Error",'table_info'=>$table_info));
					}
				}							
			}		
		}
	}

	//Import Time log  
	public function do_excel_timelog_import($import_id){
		$filename = dirname(__FILE__)."/php_excel/PHPExcel/IOFactory.php";   
		include($filename);
		if($import_id < 0){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}
		$excel_path_qry    = 'select * from cw_import where import_id = "'.$import_id.'"';
		$excel_path_info   = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
		$excel_path_result = $excel_path_info->result();
		$excel_path_info->next_result();
		if(!$excel_path_result){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}else{
			$excel_file_path    = $excel_path_result[0]->excel_file_path;
			$module_id          = $excel_path_result[0]->module_id;
			$excel_format       = $excel_path_result[0]->excel_format;
			$excel_sheet_name   = (int)$excel_path_result[0]->excel_sheet_name;
			$excel_row_start    = (int)$excel_path_result[0]->excel_start_row;
			$excel_row_end      = (int)$excel_path_result[0]->excel_end_row;
			$format_qry 	    = 'select * from cw_util_excel_format where prime_excel_format_id = "'.$excel_format.'" and cw_util_excel_format.trans_status = 1';
			$format_info    = $this->db->query("CALL sp_a_run ('SELECT','$format_qry')");
			$format_rslt    = $format_info->result();
			$format_info->next_result();
			if(!$format_rslt){
				return json_encode(array('success' => false, 'message' => "Please add excel format before import"));
			}else{
				$exist_column_name = explode(",",$format_rslt[0]->exist_column_name);
				$excel_format_qry 	= 'select IFNULL(pick_list_import,0) as pick_list_import,view_name,duplicate_data,picklist_data,field_type,pick_table,pick_list_type,pick_list,mandatory_field,field_isdefault,excel_line_column_name,excel_line_value from cw_util_excel_format_line inner join cw_form_setting on label_name = excel_line_column_name where excel_line_module_id = "'.$module_id.'" and prime_excel_format_id = "'.$excel_format.'" and cw_form_setting.prime_module_id = "'.$module_id.'" and cw_util_excel_format_line.trans_status = 1';		
				$excel_format        = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
				$excel_format_result = $excel_format->result();
				$excel_format->next_result();
				if(!$excel_format_result){
					return json_encode(array('success' => false, 'message' => "Please map excel cell column before import"));
				}else{
					try{
						$excel_obj = \PhpOffice\PhpSpreadsheet\IOFactory::load($excel_file_path);
					}catch(Exception $e){
						die('Error loading file "' . pathinfo($excel_file_path, PATHINFO_BASENAME). '": ' . $e->getMessage());
						return json_encode(array('success' => false, 'message' => "Invalid file or path"));
					}
					$sheet           = $excel_obj->getSheet($excel_sheet_name);
					if($excel_row_end){
						$total_rows = $excel_row_end;
					}else{
						$total_rows = $sheet->getHighestRow();
					}
					
					//LOAN DATA VALIDATION MANDATORY FILED AND 
					$err_column_array    = array();
					$err_column_tabview  = array();
					foreach($excel_format_result as $excel_info){
						$mandatory_field         = (int)$excel_info->mandatory_field;
						$field_type              = (int)$excel_info->field_type;
						$excel_line_column_name  = $excel_info->excel_line_column_name;
						$excel_line_value        = $excel_info->excel_line_value;
						$view_name               = $excel_info->view_name;
						$pick_table              = $excel_info->pick_table;
						$pick_list_type          = (int)$excel_info->pick_list_type;
						$pick_list               = $excel_info->pick_list;
						$picklist_data           = (int)$excel_info->picklist_data;
						$pick_list_import        = (int)$excel_info->pick_list_import;
						
						$common_multi_cell_value = $sheet->rangeToArray("$excel_line_value$excel_row_start:$excel_line_value$total_rows", NULL, TRUE, TRUE, TRUE);
						$i = $excel_row_start;
						foreach($common_multi_cell_value as $common_value){
							foreach($common_value as $col_key =>$col_value){
								if(empty($col_value) && !is_numeric($col_value)){
									$err_column_array['error']["$excel_line_value$i"] = $view_name;
									$msg_line = "columns are empty and invalid data is present please check it?";
									$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
								}elseif((int)$field_type === 5 || (int)$field_type === 7){
									if($pick_list_import !== 1){
										if($pick_list_type === 1){
											if($excel_line_column_name === "employee_code" || $excel_line_column_name === "user_id"){
												$emp_code_qry = 'select count(*) as rslt_count from cw_employees where trans_status = 1 and device_code = "'.$col_value.'"';
												$emp_data  = $this->db->query("CALL sp_a_run ('SELECT','$emp_code_qry')");
												$emp_data_result = $emp_data->result();
												$emp_data->next_result();
												$rslt_count = $emp_data_result[0]->rslt_count;
												if((int)$rslt_count === 0){
													$err_column_array['error']["$excel_line_value$i"] = $view_name;
													$msg_line = "is not exit in employee master please check it?";
													$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
												}
											}else{
												$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 '.$pick_list_val_2.' = "'.$col_value.'"';
												$pick_data  = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
												$pick_result = $pick_data->result();
												$pick_count  = $pick_data->num_rows();
												$pick_data->next_result();
												if((int)$pick_count === 0){
													$err_column_array['error']["$excel_line_value$i"] = $view_name;
													$msg_line = "column invalid data is present please check it?";
													$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
												}
											}
										}
									}
								}elseif($field_type === 4){
									$excel_date     = $sheet->getCell("$col_key$i")->getValue();	
									$unix_date      = $this->unix_convertion($excel_date);
									if($unix_date <= 0){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
											$msg_line = "Please enter valid date... Please map The Date Format Like (DD/MM/YYYY)";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}
								}
								$i++;
							}
						}
					}
					
					$err_column_count = count($err_column_array['error'] ?? []);
					if((int)$err_column_count > 0){
						$table_info = $this->get_excel_error_ui($err_column_tabview);
						echo json_encode(array('success'=>false,'message'=>"Column Wise Error",'table_info'=>$table_info));
						exit();
					}else{
						//Unique field check
						$err_column_tabview  = array();
						$array_uniq 		= array();
						foreach ($excel_format_result as $key => $value) {
							$label_name 		= $value->label_name;
							$view_name 			= $value->view_name;
							$unique_field 		= $value->unique_field;
							$excel_line_value 	= $value->excel_line_value;
							$multi_get_cell_value = $sheet->rangeToArray("$excel_line_value$excel_row_start:$excel_line_value$total_rows", NULL, TRUE, TRUE, TRUE);

							if((int)$unique_field === 1){
								$get_duplicat_value = $sheet->rangeToArray("$excel_line_value$excel_row_start:$excel_line_value$total_rows", NULL, TRUE, TRUE, TRUE);
								$get_duplicat_value = array_map('array_filter', $get_duplicat_value ?? []);//empty remove
								$get_duplicat_value = array_filter($get_duplicat_value ?? []);
								
								foreach ($get_duplicat_value as $current_key => $current_array) {
									$get_excel_val 	= $current_array[$excel_line_value];
									$exist_query = 'select count(*) uniq_exist_count from '.$this->prime_table.' where '.$label_name.' = "'.$get_excel_val.'" and trans_status =1';
									$exist_info   = $this->db->query("CALL sp_a_run ('SELECT','$exist_query')");
									$exist_result = $exist_info->result();
									$exist_info->next_result();
									foreach ($get_duplicat_value as $search_key => $search_array) {
										if($search_array["$excel_line_value"] == $current_array["$excel_line_value"]){
											if ($search_key != $current_key) {
												$err_column_array['error']["$excel_line_value$current_key"] = $view_name;
												$msg_line = "duplicate data present in column, please check it?";
												$err_column_tabview['error']["$excel_line_value$current_key"]  = $view_name." ".$msg_line;
											}
										}
										$exist_count = $exist_result[0]->uniq_exist_count;
										$array_uniq[$label_name]['view_name'] = $view_name;
										$array_uniq[$label_name]['label_name'] = $label_name;
									}

									if((int)$exist_count > 0){
										$err_column_array['error']["$excel_line_value$current_key"] = $view_name;
										$msg_line = "Data already exists for this Column";
										$err_column_tabview['error']["$excel_line_value$current_key"]  = $view_name." ".$msg_line;
									}
								}
							}
						}
						// get module unique column 
						$uniq_field_qry  = 'select view_name,label_name from  cw_form_setting where cw_form_setting.prime_module_id = "'.$module_id.'" and input_view_type IN(1,2) and field_show = 1 and unique_field = 1 and trans_status = 1';
						$uniq_field_info = $this->db->query("CALL sp_a_run ('SELECT','$uniq_field_qry')");
						$uniq_field_rslt = $uniq_field_info->result_array();
						$uniq_field_info->next_result();
						$uniq_field_rslt = array_reduce($uniq_field_rslt, function($result, $arr){	
							    $result[$arr['label_name']] = $arr;
							    return $result;
							}, array());
						$uniq_result 	 = array_diff_key($uniq_field_rslt,$array_uniq);
						if((int)$import_type === 1){
							foreach ($uniq_result as $uniq_key => $uniq_val) {
								$label_name 	= $uniq_val['label_name'];
								$err_column_array['error']["label_name"] = $uniq_val['view_name'];
								$msg_line = "Unique Field Column Missing";
								$err_column_tabview['error'][$uniq_val['view_name']]  = $uniq_val['view_name']." ".$msg_line;
							}
						}
						$err_column_count = count($err_column_array['error'] ?? []);
						$err_column       = implode(",",(array_unique($err_column_array['error'] ?? [])) ?? []);
						if((int)$err_column_count > 0){
							$table_info = $this->get_excel_error_ui($err_column_tabview);
							echo json_encode(array('success'=>false,'message'=>"Column Wise Error",'table_info'=>$table_info));
							exit();
						}
						
						$status_array	= array();
						for($row =$excel_row_start; $row <= $total_rows; $row++) {
							$prime_column_val = "";
							$prime_cell_val   = "";
							$exist_val        = "";
							$status_info = array();
							$status_info["Excel Row"] = $row;
							$sts = TRUE;
							$email_sts = TRUE;
							foreach($excel_format_result as $excel_info){
								$field_isdefault        = (int)$excel_info->field_isdefault;
								$mandatory_field        = (int)$excel_info->mandatory_field;
								$field_type             = (int)$excel_info->field_type;
								$pick_table             = $excel_info->pick_table;
								$pick_list_type         = (int)$excel_info->pick_list_type;
								$pick_list_import       = (int)$excel_info->pick_list_import;
								$pick_list              = $excel_info->pick_list;
								$excel_line_column_name = $excel_info->excel_line_column_name;
								$excel_line_value       = $excel_info->excel_line_value;
								$get_cell_value         = ucwords(trim($sheet->getCell("$excel_line_value$row")->getValue()));
	                            if($get_cell_value){
									//FOR MOBILE NUMBER
									 if($field_type === 11){
										$length = strlen($get_cell_value);
										// Validate mobile number
    									if (!(int)$this->validateMobileNumber($get_cell_value)) {
    									    $sts = false;
    									    // $validation_error = "Invalid mobile number";
    									}
										$length_query = 'select field_length from cw_form_setting where cw_form_setting.prime_module_id = "'.$module_id.'" and cw_form_setting.field_type = 11';
										$length_data  = $this->db->query("CALL sp_a_run ('SELECT','$length_query')");
										$length_result = $length_data->result();
										$length_data->next_result();
										$field_length = $length_result[0]->field_length;
										if($field_length != $length){
											$sts = FALSE;
										}
									}else 
									if($field_type === 12){
										//FOR EMAIL
										$email = $get_cell_value;
										if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
											$email_sts = FALSE;
										}
									}else
									if($field_type === 4){
										// FOR DATE
										$get_cell_value = trim(Date::excelToDateTimeObject((int)$sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));
									}else
									if($field_type === 13){
										$get_cell_value = trim(Date::excelToDateTimeObject($sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d H:i:s'));
									}else
									// FOR PICKLIST CHECK
									if(($field_type === 5) || ($field_type === 7)){
										if($pick_list_type === 1){
											$pick_list_val   = explode(",",$pick_list);
											$pick_list_val_1 = $pick_list_val[0];
											$pick_list_val_2 = $pick_list_val[1];
											$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
											if($pick_list_import === 1){
												$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_1.' = "'.$get_cell_value.'"';	
											}else{
												$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
											}	
											$pick_data  = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
											$pick_result = $pick_data->result();
											$pick_count  = $pick_data->num_rows();
											$pick_data->next_result();
											if((int)$pick_count === 1){
												if($pick_table !== $this->prime_table){
													$pick_id     = $pick_result[0]->$pick_list_val_1;
													$pick_status = (int)$pick_result[0]->trans_status;
													if($pick_status === 0){
														$upd_query  = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = "'.$pick_id.'"';
														$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
													}
													$get_cell_value = $pick_id;
												}
											}
										}else
										if($pick_list_type === 2){
											$pick_list_val_1 = $pick_table."_id";
											$pick_list_val_2 = $pick_table."_value";
											$pick_list_val_3 = $pick_table."_status";
											$pick_query = 'select * from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
											$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
											$pick_result = $pick_data->result();
											$pick_count  = $pick_data->num_rows();
											$pick_data->next_result();
											if((int)$pick_count === 0){
												$ins_query  = 'insert into '.$pick_table.'('.$pick_list_val_2.') VALUES ("'.$get_cell_value.'")';
												$ins_info   = $this->db->query("CALL sp_a_run ('INSERT','$ins_query')");
												$ins_result = $ins_info->result();
												$ins_info->next_result();
												$get_cell_value  = $ins_result[0]->ins_id;
											}else
											if((int)$pick_count === 1){
												$pick_id     = $pick_result[0]->$pick_list_val_1;
												$pick_status = (int)$pick_result[0]->$pick_list_val_3;
												if($pick_status === 0){
													$upd_query  = 'update '.$pick_table.' set '.$pick_list_val_3.' = 1 where '.$pick_list_val_1.' = '.$pick_id;
													$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
												}
												$get_cell_value = $pick_id;
											}
										}
									}
									if($field_isdefault === 1){
										//$status_info[$excel_line_column_name] = $get_cell_value;
										$get_cell_value    = str_replace("'",'^', $get_cell_value);
										$prime_column_val .= $excel_line_column_name . ",";
										$prime_cell_val   .= "\'" . $get_cell_value . "\',";
										if(empty($exist_column_name)){
											 if($mandatory_field === 1){
												$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
											}
										}else{
											if(in_array($excel_line_column_name,$exist_column_name)){
												$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
											}
										}
									}
								}
							}
							if($prime_column_val){
								$prime_id    = "prime_".$module_id."_id";
								$exist_val   = rtrim($exist_val," and ");
								$exist_query = "select count(*) exist_count,$this->prime_table.trans_status,$this->prime_table.$prime_id from $this->prime_table where $exist_val";
								$exist_info   = $this->db->query("CALL sp_a_run ('RUN','$exist_query')");
								$exist_result = $exist_info->result();
								$exist_info->next_result();
								$exist_count = $exist_result[0]->exist_count;
								$created_on  = date("Y-m-d h:i:s");
								if(!$sts){
									$status_info['status'] = "Invalid Mobile Number";
								}else
								if(!$email_sts){
									$status_info['status'] = "Invalid Email";
								}else
								if((int)$exist_count === 0){
									$prime_column_val .= "trans_created_by,trans_created_date";
									$prime_cell_val   .= '"'.$this->logged_id.'",'.'"'.$created_on.'"';
									$prime_column_val  = rtrim($prime_column_val,",");
									$prime_cell_val    = rtrim($prime_cell_val,",");
									$prime_query       = "insert into $this->prime_table ($prime_column_val) VALUES ($prime_cell_val)";
									$insert_info       = $this->db->query("CALL sp_a_run ('INSERT','$prime_query')");
									$insert_result     = $insert_info->result();
									$insert_info->next_result();
									$insert_id = $insert_result[0]->ins_id;
									
									$status_info['Status'] = "Inserted to DB";
								}else
								if((int)$exist_count === 1){
									$trans_status = (int)$exist_result[0]->trans_status;
									$upd_prime_id = (int)$exist_result[0]->$prime_id;
									if($trans_status === 0){
										$upd_query = 'UPDATE '.$this->prime_table.' SET trans_updated_by = "'.$this->logged_id.'",trans_updated_date = "'.$created_on.'" , trans_status = 1 WHERE '.$prime_id.' = "'.$upd_prime_id.'"';
										$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
										$status_info['status'] = "Changed to active";
									}else{
										$status_info['status'] = "Already Exist in DB";
									}							
								}else{
									$status_info['status'] = "Already Exist in DB";
								}
								$status_array[] = $status_info;
							}
						}
						$table_info = $this->get_excel_import_ui($status_array);
						return json_encode(array('success'=>true,'message'=>"Successfully file imported",'table_info'=>$table_info));
					}
				}
			}
		}
	}

	//import validation and checking updated
	public function do_excel_ot_request_import($import_id,$category,$process_month){

		//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));	
		$ending_date           = date('Y-m-d',strtotime($financial_info[0]->ending_date));	

		$salary_info_arr       = $this->salary_start_end_info($category,$process_month);

		$salary_start_date     = date('Y-m-d',strtotime($salary_info_arr['salary_start_date']));
		$salary_end_date       = date('Y-m-d',strtotime($salary_info_arr['salary_end_date']));
		$emp_name_arr          = ""; 
		$shift_import_arr      = "";
		$shift_name_arr        = "";
		$created_on            = date('Y-m-d H:i:s');
		$filename              = dirname(__FILE__)."/php_excel/PHPExcel/IOFactory.php";
		include($filename);
		if($import_id < 0){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}
		//
		$excel_path_qry    = 'select * from cw_import where import_id = "'.$import_id.'"';
		$excel_path_info   = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
		$excel_path_result = $excel_path_info->result();
		$excel_path_info->next_result();
		if(!$excel_path_result){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}else{
			$excel_file_path    = $excel_path_result[0]->excel_file_path; 
			$module_id          = $excel_path_result[0]->module_id;
			$excel_format       = $excel_path_result[0]->excel_format;
			$excel_sheet_name   = (int)$excel_path_result[0]->excel_sheet_name;
			$excel_row_start    = (int)$excel_path_result[0]->excel_start_row;
			$excel_row_end      = (int)$excel_path_result[0]->excel_end_row;
			
			$format_qry 	= 'select * from cw_util_excel_format where prime_excel_format_id = "'.$excel_format.'" and cw_util_excel_format.trans_status = 1';
			$format_info    = $this->db->query("CALL sp_a_run ('SELECT','$format_qry')");
			$format_rslt    = $format_info->result();
			$format_info->next_result();
			if(!$format_rslt){
				return json_encode(array('success' => false, 'message' => "Please add excel format before import"));
			}else{
				$exist_column_name = explode(",",$format_rslt[0]->exist_column_name);
				$excel_format_qry 	= 'select field_type,pick_table,pick_list_type,pick_list_import,pick_list,mandatory_field,field_isdefault,excel_line_column_name,excel_line_value from cw_util_excel_format_line inner join cw_form_setting on label_name = excel_line_column_name where excel_line_module_id = "'.$module_id.'" and prime_excel_format_id = "'.$excel_format.'" and cw_form_setting.prime_module_id = "'.$module_id.'" and cw_util_excel_format_line.trans_status = 1';			
				$excel_format        = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
				$excel_format_result = $excel_format->result();
				$excel_format->next_result();
				if(!$excel_format_result){
					
					return json_encode(array('success' => false, 'message' => "Please map excel cell column before import"));
				}else{
					try{
						$excel_obj = \PhpOffice\PhpSpreadsheet\IOFactory::load($excel_file_path);
					}catch(Exception $e){
						die('Error loading file "' . pathinfo($excel_file_path, PATHINFO_BASENAME). '": ' . $e->getMessage());
						return json_encode(array('success' => false, 'message' => "Invalid file or path"));
					}
				
					$sheet           = $excel_obj->getSheet($excel_sheet_name);
					if($excel_row_end){
						$total_rows  = $excel_row_end;
					}else{
						$total_rows  = $sheet->getHighestRow();
					}

					$employee_codes_arr = $this->get_excel_employee_codes($sheet,$excel_row_start,$total_rows,$excel_format_result,$module_id);
					$employee_count 	= count($employee_codes_arr['employee_codes_arr'] ?? []); 

					if((int)$employee_count <= 0){
						echo json_encode(array('success'=>false,'message'=>"Please check Employee Code Column in your Excel Sheet...",'table_info'=>""));
						exit(0);
					}
					$employee_codes     = trim(implode('","',$employee_codes_arr['employee_codes_arr'] ?? []));

					$emp_name_qry       = 'select employee_code,role as category,emp_name,date_of_joining,department,approve_type,first_level_approval,second_level_approval,termination_status,resignation_date from cw_employees where trans_status = 1 and employee_code in ("'.$employee_codes.'")';
					$emp_name_info      = $this->db->query("CALL sp_a_run ('RUN','$emp_name_qry')");
					$emp_name_result    = $emp_name_info->result_array();
					$emp_name_info->next_result();

					$emp_name_arr       = array();
					foreach($emp_name_result as $emp_key => $emp_val){
						$emp_code                 = $emp_val['employee_code'];
						$emp_name_arr[$emp_code]  = $emp_val;
					}

					//time entry details for that entry date
					$time_entry_qry  = 'select employee_code,att_date,entry_flag,update_flag,date_format(cw_time_entry.punch_in, "%H:%i") as punch_in,date_format(cw_time_entry.punch_out, "%H:%i") as punch_out,if(cw_time_entry.early_in > 0, time_format(concat(floor(cw_time_entry.early_in/60),":",lpad(mod(cw_time_entry.early_in,60),2,"0")),"%H:%i"), cw_time_entry.early_in) as early_in,if(cw_time_entry.excess_out > 0, time_format(concat(floor(cw_time_entry.excess_out/60),":",lpad(mod(cw_time_entry.excess_out,60),2,"0")),"%H:%i"), cw_time_entry.excess_out) as excess_out,if(cw_time_entry.total_excess_hours > 0, time_format(concat(floor(cw_time_entry.total_excess_hours/60),":",lpad(mod(cw_time_entry.total_excess_hours,60),2,"0")),"%H:%i"), cw_time_entry.total_excess_hours) as total_excess_hours,whole_day_status,shift_id,cw_shift_master.shift_name,cw_shift_master.from_time,cw_shift_master.to_time,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,break_deduction from cw_time_entry inner join cw_shift_master on cw_shift_master.prime_shift_master_id = cw_time_entry.shift_id where att_date between "'.$salary_start_date.'" and "'.$salary_end_date.'" and cw_time_entry.trans_status = 1 and cw_time_entry.employee_code in ("'.$employee_codes.'")';
					$time_entry_info = $this->db->query("CALL sp_a_run ('SELECT','$time_entry_qry')");
					$time_entry_rslt = $time_entry_info->result_array();
					$time_entry_info->next_result();	

					$time_entry_arr  = array();	
					foreach($time_entry_rslt as $time_key => $time_val){
						$time_emp_code    = $time_val['employee_code'];
						$time_att_date    = $time_val['att_date'];
						$time_entry_arr[$time_emp_code][$time_att_date]  = $time_val;
					}

					$highest_column       = $sheet->getHighestColumn();
					$worksheetTitle       = $sheet->getTitle();
					$status_array	      = array();
					$leave_creation_arr   = array();
					$opening_used_arr     = array();
					$opening_arr	      = array();
					$excel_exist_arr      = array();
					$del_req_ins_arr      = array();
					$prime_query_value    = "";
					$prime_upd_value      = "";
					
					for($row =$excel_row_start; $row <= $total_rows; $row++) {
						$prime_column_val = "";
						$prime_cell_val   = "";
						$exist_val        = "";
						$status_info      = array();
						$status_info["Excel Row"] = $row;
						$sts              = TRUE;
						$email_sts        = TRUE;
						$picklist_sts     = TRUE;
						$app_sts          = TRUE;
						$exist_count      = 0;
						foreach($excel_format_result as $excel_info){
							$field_isdefault        = (int)$excel_info->field_isdefault;
							$mandatory_field        = (int)$excel_info->mandatory_field;
							$field_type             = (int)$excel_info->field_type;
							$pick_table             = $excel_info->pick_table;
							$pick_list_type         = (int)$excel_info->pick_list_type;
							$pick_list_import       = (int)$excel_info->pick_list_import;
							$pick_list              = $excel_info->pick_list;
							$excel_line_column_name = $excel_info->excel_line_column_name;
							$excel_line_value       = $excel_info->excel_line_value;

							$get_cell_value         = ucwords(trim($sheet->getCell("$excel_line_value$row")->getValue()));
                            if($get_cell_value){
								//FOR MOBILE NUMBER
								 if($field_type === 11){
									$length = strlen($get_cell_value);
									$length_query = 'select field_length from cw_form_setting where cw_form_setting.prime_module_id = "'.$module_id.'" and cw_form_setting.field_type = 11';
									$length_data  = $this->db->query("CALL sp_a_run ('SELECT','$length_query')");
									$length_result = $length_data->result();
									$length_data->next_result();
									$field_length = $length_result[0]->field_length;
									if($field_length != $length){
										$sts = FALSE;
									}									
								}else 
								if($field_type === 12){
									//FOR EMAIL
									$email = $get_cell_value;
									if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
										$email_sts = FALSE;
									}
								}else
								if($field_type === 4){
									// FOR DATE
									$get_cell_value = trim(Date::excelToDateTimeObject((int)$sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));
								}else
								if($field_type === 13){
									// $get_cell_value = trim(date('Y-m-d H:i:s',Date::PHPToExcel($sheet->getCell("$excel_line_value$row")->getValue())));
								}else
								// FOR PICKLIST CHECK
								if(($field_type === 5) || ($field_type === 7)){
									if($pick_list_type === 1){
										$pick_list_val   = explode(",",$pick_list);
										$pick_list_val_1 = $pick_list_val[0];
										$pick_list_val_2 = $pick_list_val[1];
										$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'" and '.$pick_table.'.trans_status = 1';
										if($pick_list_import === 1){
											$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_1.' = "'.$get_cell_value.'" and '.$pick_table.'.trans_status = 1';	
										}else{
											$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'" and '.$pick_table.'.trans_status = 1';
										}	
										$pick_data  = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
										$pick_result = $pick_data->result();
										$pick_count  = $pick_data->num_rows();
										$pick_data->next_result();
										if((int)$pick_count === 0){
											$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
											$exist_count     = 1;
										}else
										if((int)$pick_count === 1){
											if($pick_table !== $this->prime_table){
												$pick_id     = $pick_result[0]->$pick_list_val_1;
												$pick_status = (int)$pick_result[0]->trans_status;
												if($pick_status === 0){
													$upd_query  = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = '.$pick_id;
													$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
												}
												$get_cell_value = $pick_id;
											}
										}
									}else
									if($pick_list_type === 2){
										$pick_list_val_1 = $pick_table."_id";
										$pick_list_val_2 = $pick_table."_value";
										$pick_list_val_3 = $pick_table."_status";
										$pick_query = 'select * from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'" and '.$pick_table.'.trans_status = 1';
										$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
										$pick_result = $pick_data->result();
										$pick_count  = $pick_data->num_rows();
										$pick_data->next_result();
										if((int)$pick_count === 0){
											$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
											$exist_count    = 1;
										}else
										if((int)$pick_count === 1){
											$pick_id        = $pick_result[0]->$pick_list_val_1;
											$pick_status    = (int)$pick_result[0]->$pick_list_val_3;
											if($pick_status === 0){
												$upd_query  = 'update '.$pick_table.' set '.$pick_list_val_3.' = 1 where '.$pick_list_val_1.' = '.$pick_id;
												$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
											}
											$get_cell_value = $pick_id;
										}
									}
								}
								if($field_isdefault === 1){
									if($excel_line_column_name === 'employee_code'){
										$employee_code     = $get_cell_value;
										$emp_code_col_name = $excel_line_value;
										$employee_name     = $emp_name_arr[$employee_code]['emp_name'];
										$check_emp_code    = $emp_name_arr[$employee_code]['employee_code'];
										$category          = $emp_name_arr[$employee_code]['category'];
										$emp_doj           =  date("Y-m-d",strtotime($emp_name_arr[$employee_code]['date_of_joining']));
										$approve_type      = $emp_name_arr[$employee_code]['approve_type'];
										$department        = $emp_name_arr[$employee_code]['department'];
										$active_sts        = (int)$emp_name_arr[$employee_code]['termination_status'];
										$resign_date       = date("Y-m-d",strtotime($emp_name_arr[$employee_code]['resignation_date']));
										$first_level       = $emp_name_arr[$employee_code]['first_level_approval'];
										$second_level      = $emp_name_arr[$employee_code]['second_level_approval'];
										$applied_on        = date('Y-m-d');
										
									}
									if($excel_line_column_name === 'shift_name'){
										$shift_name        = $get_cell_value;
									}
									if($excel_line_column_name === "entry_date"){
										$dis_entry_date       = date('d-m-Y',strtotime($get_cell_value));
										$entry_date           = date('Y-m-d',strtotime($get_cell_value));
										$entry_date_col_name  = $excel_line_value;
									}
									if($excel_line_column_name === "ot_in_time"){
										$in_time_col_name     = $excel_line_value;
										if($get_cell_value === "" || $get_cell_value === "00:00"){
											(int)$exist_count += 1;
											if($exist_count === 1){
												$err_column_array['error']["$excel_line_value$row"] = "OT In Time should not Zero or Empty..!!";
												$exist_count++;
											}
										}else{
											$get_datetime = trim(date('H:i',Date::PHPToExcel($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
											$newhours     = date('H:i', strtotime($get_datetime. ' -5 hours'));
											$ot_in_time   = date('H:i', strtotime($newhours. ' -30 minutes'));
										}
									}
									if($excel_line_column_name === "ot_out_time"){
										$out_time_col_name     = $excel_line_value;
										if($get_cell_value === "" || $get_cell_value === "00:00"){
											(int)$exist_count += 1;
											if($exist_count === 1){
												$err_column_array['error']["$excel_line_value$row"] = "OT Out Time should not Zero or Empty..!!";
												$exist_count++;
											}
										}else{
											$get_datetime = trim(date('H:i',Date::PHPToExcel($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
											$newhours     = date('H:i', strtotime($get_datetime. ' -5 hours'));
											$ot_out_time  = date('H:i', strtotime($newhours. ' -30 minutes'));
										}
									}
									if($excel_line_column_name === "reason"){
										$reason         = $get_cell_value;
									}
								}
							}else{
								(int)$exist_count += 1;
								if($exist_count === 1){
									
									$err_column_array['error']["$row"] = "please Map All Excel Column Data..!";
									$exist_count++;
								}
							}
						}
if(!$check_emp_code){
	$err_column_array['error']["$emp_code_col_name$row"] = "Employee Code ($employee_code) or Employee Name not Present in the Employee Master?";
}else{
	$check_ot_exist_qry    = 'select count(prime_overtime_entry_id) as count from cw_overtime_entry where cw_overtime_entry.employee_code = "'.$employee_code.'" and approval_status in (1,2) and cw_overtime_entry.entry_date  = "'.$entry_date.'" and cw_overtime_entry.ot_type = "1" and cw_overtime_entry.trans_status = 1';
	// and cw_overtime_entry.ot_type = "'.$ot_type.'"
	$check_ot_exist_info   = $this->db->query("CALL sp_a_run ('SELECT','$check_ot_exist_qry')");
	$check_ot_exist_rslt   = $check_ot_exist_info->result();
	$check_ot_exist_info->next_result();
	$ot_exist_count        = (int)$check_ot_exist_rslt[0]->count;

	if($ot_exist_count){
		$err_column_array['error']["$entry_date_col_name$row"] = "Same Attendance Date Already Exist in Overtime Entry Table Please Check it..!!";
	}else{
	//GET EMLOYEE DATE OF JOINING
if($emp_doj){
	if($emp_doj > $entry_date){
		(int)$exist_count += 1;
		if($exist_count === 1){
			$err_column_array['error']["$entry_date_col_name$row"] = "Attendance Date Should not be Greater than Date of Joining Please Check it..!!";
			$exist_count++;
		}
	}else{
		if($active_sts === 1){
			if($resign_date){
				if($resign_date < $salary_start_date){
					(int)$exist_count += 1;
					if($exist_count === 1){
						$err_column_array['error']["$emp_code_col_name$row"] = "Don't Import a Resigned Employee for this Attendance Month? Please Check it..!!";
						$exist_count++;
					}
				}
			}else{
				(int)$exist_count += 1;
				if($exist_count === 1){
					$err_column_array['error']["$emp_code_col_name$row"] = "Please Map Resigned Date for this Employee? Please Check it..!!";
					$exist_count++;
				}
			}
		}
		if($entry_date){
			if($entry_date < $salary_start_date || $entry_date > $salary_end_date){
				(int)$exist_count += 1;
				if($exist_count === 1){
					$err_column_array['error']["$entry_date_col_name$row"] = "Attendance Date not Valid for this Salary Start Date and End Date? Please Check it..!!";
					$exist_count++;
				}
			}else{
				//check ot approval or not from time entry table 
				if(!$time_entry_arr[$employee_code][$entry_date]){
					(int)$exist_count += 1;
					if($exist_count === 1){
						$err_column_array['error']["$entry_date_col_name$row"] = "In this Date this Employee not Available in OT Approval Please Check it Attendance Table..!!";
						$exist_count++;
					}
				}else
				if($excel_exist_arr[$employee_code][$entry_date]){
					(int)$exist_count += 1;
					if($exist_count === 1){

						$err_column_array['error']["$entry_date_col_name$row"] = "Same Data Already Exist In Your Excel Sheet for this Attenance Date..!!";
						$exist_count++;
					}
				}else{
					$shift_name         = $time_entry_arr[$employee_code][$entry_date]['shift_id'];

					$shift_status     = (int)$time_entry_arr[$employee_code][$entry_date]['shift_status'];

					$break_deduction  = (int)$time_entry_arr[$employee_code][$entry_date]['break_deduction'];

					//$break_deduction  = (int)$time_entry_arr[$employee_code][$entry_date]['total_excess_hours'];

					$shift_start      = (int)$time_entry_arr[$employee_code][$entry_date]['shift_start'];

					$shift_end        = (int)$time_entry_arr[$employee_code][$entry_date]['shift_end'];

					$whole_day_status = $time_entry_arr[$employee_code][$entry_date]['whole_day_status'];

					$shift_from_time  = date("H:i",strtotime($time_entry_arr[$employee_code][$entry_date]['from_time']));

					$shift_to_time    = date("H:i",strtotime($time_entry_arr[$employee_code][$entry_date]['to_time']));

					$import_in_time   = date("H:i",strtotime($time_entry_arr[$employee_code][$entry_date]['import_in_time']));

					$import_out_time  = date("H:i",strtotime($time_entry_arr[$employee_code][$entry_date]['import_out_time']));

					$punch_in         =  date("H:i",strtotime($time_entry_arr[$employee_code][$entry_date]['punch_in']));

					$punch_out        =  date("H:i",strtotime($time_entry_arr[$employee_code][$entry_date]['punch_out']));
					
					$early_in         = date("H:i",strtotime($time_entry_arr[$employee_code][$entry_date]['early_in']));
					$excess_out       = date("H:i",strtotime($time_entry_arr[$employee_code][$entry_date]['excess_out']));

					$import_in_date   = date("Y-m-d H:i",strtotime($entry_date.' '.$import_in_time));
					$import_out_date  = date("Y-m-d H:i",strtotime($entry_date.' '.$import_out_time));
					$punch_in_date    = date("Y-m-d H:i",strtotime($entry_date.' '.$punch_in));
					$punch_out_date   = date("Y-m-d H:i",strtotime($entry_date.' '.$punch_out));
					$ot_in_date       = date("Y-m-d H:i",strtotime($entry_date.' '.$ot_in_time));
					$ot_out_date      = date("Y-m-d H:i",strtotime($entry_date.' '.$ot_out_time));
					// if($min_ot_hours){
					// 	$min_ot_time  = date("H:i",strtotime($min_ot_hours));
					// }else{
					// 	(int)$exist_count += 1;
					// 	if($exist_count === 1){
					// 		$err_column_array['error']["$row"] = "In Permission Setting to Set Minimum Excess OT Hours Value for this Shift and Category? Please Contact Admin..!!";
					// 		$exist_count++;
					// 	}
					// }
					$total_excess_hrs = "";
					if($time_entry_arr[$employee_code][$entry_date]['total_excess_hours']){
						$total_excess_hrs = date("H:i",strtotime($time_entry_arr[$employee_code][$entry_date]['total_excess_hours']));
					}else{
						(int)$exist_count += 1;
						if($exist_count === 1){
							$err_column_array['error']["$entry_date_col_name$row"] = "In this Attenedance Date Total OT Hours Should not Empty or Zero Please Check it..!!";
							$exist_count++;
						}
					}
					if($punch_in && $punch_out && $ot_in_time && $ot_out_time && $total_excess_hrs){
						if($shift_start === 2){
							$import_in_date  = date("Y-m-d H:i",strtotime("+1 day",strtotime($entry_date.' '.$import_in_time)));
							$punch_in_date   =  date("Y-m-d H:i",strtotime("+1 day",strtotime($entry_date.' '.$punch_in)));
							$ot_in_date      =  date("Y-m-d H:i",strtotime("+1 day",strtotime($entry_date.' '.$ot_in_time)));
						}else
						if($shift_start === 3){
							$import_in_date = date("Y-m-d H:i",strtotime("-1 day",strtotime($entry_date.' '.$import_in_time)));
							if($import_in_time <= $punch_in){
								$punch_in_date    =  date("Y-m-d H:i",strtotime("-1 day",strtotime($entry_date.' '.$punch_in)));
							}
							if($import_in_time <= $ot_in_time){
								$ot_in_date  = date("Y-m-d H:i",strtotime("-1 day",strtotime($entry_date.' '.$ot_in_time)));
							}	
								
						}
						if($shift_end === 2){
							$import_out_date = date("Y-m-d H:i",strtotime("+1 day",strtotime($entry_date.' '.$import_out_time)));
							if($import_out_time >= $punch_out){
								$punch_out_date        = date("Y-m-d H:i",strtotime("+1 day",strtotime($entry_date.' '.$punch_out)));
							}
							if($import_out_time >= $ot_out_time){
								$ot_out_date  = date("Y-m-d H:i",strtotime("+1 day",strtotime($entry_date.' '.$ot_out_time)));
							}
						}else
						if($shift_end === 3){
							$import_out_date = date("Y-m-d H:i",strtotime("-1 day",strtotime($entry_date.' '.$import_out_time)));
							$punch_out_date  = date("Y-m-d H:i",strtotime("-1 day",strtotime($entry_date.' '.$punch_out)));
							$ot_out_date  = date("Y-m-d H:i",strtotime("-1 day",strtotime($entry_date.' '.$ot_out_time)));
							
						}
						//IMPORT START DATE CURRENT DATE
						if($shift_status === 2){
							//IMPORT START DATE CURRENT DATE
							if($shift_start === 1){
								//SHIFT IN TIME CURRENT DATE AND SHIFT OUT TIME NEXT DATE(REQUEST SEND IN DATE WAS NEXT DATE SO TAKE ON SHIFT IN DATE WAS NEXT DATE)
								if($punch_in > $punch_out && $punch_in > $ot_in_time){
									$ot_in_date   = date("Y-m-d H:i",strtotime("+1 day",strtotime($entry_date.' '.$ot_in_time)));
								}	
							}
						}
						// if($punch_in_date > $ot_in_date){
						if($punch_in_date > $ot_in_date || $punch_out_date <= $ot_in_date){
						// if($punch_in_date > $ot_in_date && $punch_out_date < $ot_in_date){
							(int)$exist_count += 1;
							if($exist_count === 1){
								$err_column_array['error']["$in_time_col_name$row"] = "Ot In Time should add Between Punch In Time and Out Time.!";
								$exist_count++;
							}
						}
						/*else
						if($punch_out_date <= $ot_in_date){
							(int)$exist_count += 1;
							if($exist_count === 1){
								$err_column_array['error']["$in_time_col_name$row"] = "Ot In Time Should not be Greater than Punch Out Time..!!";
								$exist_count++;
							}
						}*/
						else
						if($punch_in_date >= $ot_out_date || $punch_out_date < $ot_out_date){
							// $punch_in_date >= $ot_out_date
							(int)$exist_count += 1;
							if($exist_count === 1){
								$err_column_array['error']["$out_time_col_name$row"] = "OT Out Time should add Between Punch In Time and Out Time.!";
								$exist_count++;
							}
						}
						/*else
						if($punch_out_date < $ot_out_date){
							(int)$exist_count += 1;
							if($exist_count === 1){
								$err_column_array['error']["$out_time_col_name$row"] = "OT Out Time should not be Greater than Punch Out Time..!!";
								$exist_count++;
							}
						}*/
						else{
						if(($entry_flag === "U" || $update_flag === "U") && ($entry_flag !== "W" && $update_flag !== "W")){
							(int)$exist_count += 1;
							if($exist_count === 1){
								$err_column_array['error']["$entry_date_col_name$row"] = "On this Attendance Date You are not Eligible for Apply OT Request.!Please Check it.!";
								$exist_count++;
							}
						}else{
						if($ot_in_date && $ot_out_date){
							//to calculate total hours with two dates
							$date_arr    = date_diff(date_create($ot_in_date), date_create($ot_out_date));
							$time_hr     = $date_arr->h;
							$time_min    = $date_arr->i;
							//total_hours get in hours and minutes format
							$total_hours = date("H:i",strtotime($time_hr.":".$time_min));

							if(!$total_excess_hrs){
								(int)$exist_count += 1;
								if($exist_count === 1){
									$err_column_array['error']["$entry_date_col_name$row"] = "In this Attendance Date Total Excess Hours should not Empty? Please Check..!";
									$exist_count++;
								}
							}else{
								if($total_excess_hrs < $total_hours){
										(int)$exist_count += 1;
									if($exist_count === 1){
										$err_column_array['error']["$row"] = "Total OT Hours should not Exceeded the Excess Hours ..!";
										$exist_count++;
									}
								}else{
									$total_hours_ot       = $this->decimalHours($total_hours);
									$break_deduction_ot   = $this->decimalHours($break_deduction);
									$ot_hours             = $total_hours_ot - $break_deduction;
									$ot_hours             = $this->convertDecimalHoursToTime($ot_hours);
									$prime_req_value      = '"'.$employee_code.'","'.$category.'","'.$emp_doj.'","'.$department.'","'.$approve_type.'","'.$first_level.'","'.$second_level.'","'.$applied_on.'","'.$entry_date.'","'.$shift_name.'","'.$punch_in.'","'.$punch_out.'","'.$ot_in_time.'","'.$ot_out_time.'","'.$early_in.'","'.$excess_out.'","'.$total_hours.'","00:00:00","1","'.$shift_status.'","1","1","1","'.$prime_financial_id.'","'.$reason.'","'.$this->logged_id.'","'.$created_on.'","'.$break_deduction.'","'.$ot_hours.'"';

									$prime_column_val       = "employee_code,category,date_of_joining,department,approval_type,first_level_approval,second_level_approval,applied_on,entry_date,shift_name,in_time,out_time,ot_in_time,ot_out_time,early_coming,excess_out,excess_work,over_time,ot_type,shift_status,first_approval_status,second_approval_status,approval_status,financial_setting_id,reason,trans_created_by,trans_created_date,break_deduction,ot_hours";

									$request_ins_qry  = "insert into cw_overtime_request ($prime_column_val) VALUES ($prime_req_value)";					
									$request_ins_info = $this->db->query("CALL sp_a_run ('INSERT','$request_ins_qry')");
									$request_ins_rslt = $request_ins_info->result();
									$request_ins_info->next_result();

									$insert_id        = (int)$request_ins_rslt[0]->ins_id;
									//arrya push use to delete a request inserted data
									array_push($del_req_ins_arr,$insert_id);

									if($insert_id){
										$excel_exist_arr[$employee_code][$entry_date] = $entry_date;

										//OT APPROVAL INSERT QRY
										$prime_app_ins_val .= '"'.$insert_id.'","'.$employee_code.'","'.$category.'","'.$emp_doj.'","'.$department.'","'.$approve_type.'","'.$first_level.'","'.$second_level.'","'.$applied_on.'","'.$entry_date.'","'.$shift_name.'","'.$punch_in.'","'.$punch_out.'","'.$ot_in_time.'","'.$ot_out_time.'","'.$early_in.'","'.$excess_out.'","'.$total_hours.'","'.$total_hours.'","1","'.$shift_status.'","1","1","1","'.$prime_financial_id.'","'.$reason.'","'.$this->logged_id.'","'.$created_on.'"),(';

										//OT ENTRY INSERT QRY	
										$ot_entry_ins_val .= '"'.$insert_id.'","'.$prime_financial_id.'","'.$category.'","'.$employee_code.'","'.$shift_name.'","'.$shift_status.'","'.$entry_date.'","'.$punch_in.'","'.$punch_out.'","'.$ot_in_time.'","'.$ot_out_time.'","'.$early_in.'","'.$excess_out.'","'.$total_hours.'","00:00:00","1","1","'.$this->logged_id.'","'.$created_on.'"),(';

										$status_info['Status'] = "Inserted to DB";
										$status_array[] = $status_info;
									}	
										}
									}
								}
							}
						}	
					}
				}
			}
		}	
	}
		}else{
			$err_column_array['error']["$emp_code_col_name$row"] = "Please Add Date of Joining for this Employee..!!";
		}
	}		
}
}
					$err_column_count = count($err_column_array['error'] ?? []);
	
					if((int)$err_column_count > 0){
						//delete a wrong insert data from ot request table
						$del_req_ins_id = implode(',',$del_req_ins_arr ?? []);
						if($del_req_ins_id){
							$delete_query  = 'DELETE FROM cw_overtime_request  WHERE  prime_overtime_request_id in ('. $del_req_ins_id .')';
							$this->db->query("CALL sp_a_run ('RUN','$delete_query')");
						}
						$table_info = $this->get_excel_error_ui($err_column_array);

						echo json_encode(array('success'=>false,'message'=>"Data are Not Imported",'table_info'=>$table_info));
					}else{
						//FOR OT REQUEST INSERT TO OT APPROVAL TABLE
						if($prime_app_ins_val){
							$prime_app_ins_val    = rtrim($prime_app_ins_val,"),(");	
							$prime_app_ins_key    = "prime_overtime_request_id,employee_code,category,date_of_joining,department,approval_type,first_level_approval,second_level_approval,applied_on,entry_date,shift_name,in_time,out_time,ot_in_time,ot_out_time,early_coming,excess_out,excess_work,over_time,ot_type,shift_status,first_approval_status,second_approval_status,approval_status,financial_setting_id,reason,trans_created_by,trans_created_date";
							
							$approval_ins_qry     = "insert into cw_overtime_approval ($prime_app_ins_key) VALUES ($prime_app_ins_val)";						
							$approval_ins_info    = $this->db->query("CALL sp_a_run ('INSERT','$approval_ins_qry')");
							$approval_ins_rslt    = $approval_ins_info->result();
							$approval_ins_info->next_result();
							$app_ins_id           = (int)$approval_ins_rslt[0]->ins_id;
					
							//FOR OT REQUEST UPDATE TO OT ENTRY TABLE
							if($app_ins_id){
								$ot_entry_ins_val   = rtrim($ot_entry_ins_val,"),(");
								//OT ENTRY INS QUERY
								$ot_entry_ins_key   = "prime_overtime_request_id,financial_setting_id,category,employee_code,shift_name,shift_status,entry_date,in_time,out_time,ot_in_time,ot_out_time,early_coming,excess_out,excess_work,over_time,ot_type,approval_status,trans_created_by,trans_created_date";

								$ot_entry_ins_qry   = "insert into cw_overtime_entry ($ot_entry_ins_key) VALUES ($ot_entry_ins_val)";
								$ot_entry_ins_info  = $this->db->query("CALL sp_a_run ('INSERT','$ot_entry_ins_qry')");
								$ot_entry_ins_rslt  = $ot_entry_ins_info->result();
								$ot_entry_ins_info->next_result();
							}
							$table_info = $this->get_excel_import_ui($status_array);
							return json_encode(array('success'=>true,'message'=>"Successfully file imported",'table_info'=>$table_info));
						}
					}
				}
			}
		}
	}

	//Check from Time Entry
	public function check_time_entry_details($employee_code,$entry_date){
		$time_entry_qry        = 'select date_format(cw_time_entry.punch_in, "%H:%i") as punch_in,date_format(cw_time_entry.punch_out, "%H:%i") as punch_out,if(cw_time_entry.early_in > 0, time_format(concat(floor(cw_time_entry.early_in/60),":",lpad(mod(cw_time_entry.early_in,60),2,"0")),"%H:%i"), cw_time_entry.early_in) as early_in,if(cw_time_entry.excess_out > 0, time_format(concat(floor(cw_time_entry.excess_out/60),":",lpad(mod(cw_time_entry.excess_out,60),2,"0")),"%H:%i"), cw_time_entry.excess_out) as excess_out,if(cw_time_entry.total_excess_hours > 0, time_format(concat(floor(cw_time_entry.total_excess_hours/60),":",lpad(mod(cw_time_entry.total_excess_hours,60),2,"0")),"%H:%i"), cw_time_entry.total_excess_hours) as total_excess_hours,whole_day_status,shift_id,cw_shift_master.shift_name,cw_shift_master.from_time,cw_shift_master.to_time,cw_shift_master.shift_status from cw_time_entry inner join cw_shift_master on cw_shift_master.prime_shift_master_id = cw_time_entry.shift_id where cw_time_entry.employee_code = "'.$employee_code.'" and cw_time_entry.att_date = "'.$entry_date.'" and cw_time_entry.trans_status = 1 and cw_shift_master.trans_status = 1';

		$time_entry_info       = $this->db->query("CALL sp_a_run ('SELECT','$time_entry_qry')");
		$time_entry_result     = $time_entry_info->result();
		$time_entry_info->next_result();

		if($time_entry_result){
			return $time_entry_result;
		}else{
			return false;
		}
	}

	//import validation and checking updated
	public function do_excel_shift_import($import_id){
		$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;
		$starting_date        = date('Y-m-d',strtotime($leave_financial_info[0]->starting_date));	
		$ending_date          = date('Y-m-d',strtotime($leave_financial_info[0]->ending_date));	
		$emp_name_arr         = array(); 
		$shift_import_arr     = array();
		$shift_name_arr       = array();
		$time_entry_arr       = array();
		$leave_entry_arr      = array();
		$on_duty_entry_arr    = array();
		$permission_entry_arr = array();
		$mp_entry_arr         = array();
		$ot_entry_arr         = array();

		$filename             = dirname(__FILE__)."/php_excel/PHPExcel/IOFactory.php";
		include($filename);
		if($import_id < 0){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}
		
		$excel_path_qry    = 'select * from cw_import where import_id = "'.$import_id.'"';
		$excel_path_info   = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
		$excel_path_result = $excel_path_info->result();
		$excel_path_info->next_result();
		if(!$excel_path_result){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}else{
			$excel_file_path    = $excel_path_result[0]->excel_file_path;
			$module_id          = $excel_path_result[0]->module_id;
			$excel_format       = $excel_path_result[0]->excel_format;
			$excel_sheet_name   = (int)$excel_path_result[0]->excel_sheet_name;
			$excel_row_start    = (int)$excel_path_result[0]->excel_start_row;
			$excel_row_end      = (int)$excel_path_result[0]->excel_end_row;
			
			$format_qry 	= 'select * from cw_util_excel_format where prime_excel_format_id = "'.$excel_format.'" and cw_util_excel_format.trans_status = 1';
			$format_info    = $this->db->query("CALL sp_a_run ('SELECT','$format_qry')");
			$format_rslt    = $format_info->result();
			$format_info->next_result();

			if(!$format_rslt){
				return json_encode(array('success' => false, 'message' => "Please add excel format before import"));
			}else{	
				$exist_column_name = explode(",",$format_rslt[0]->exist_column_name);
				$excel_format_qry 	= 'select field_type,pick_table,pick_list_type,pick_list_import,pick_list,mandatory_field,field_isdefault,excel_line_column_name,excel_line_value from cw_util_excel_format_line inner join cw_form_setting on label_name = excel_line_column_name where excel_line_module_id = "'.$module_id.'" and prime_excel_format_id = "'.$excel_format.'" and cw_form_setting.prime_module_id = "'.$module_id.'" and cw_util_excel_format_line.trans_status = 1';			
				$excel_format        = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
				$excel_format_result = $excel_format->result();
				$excel_format->next_result();

				if(!$excel_format_result){
					return json_encode(array('success' => false, 'message' => "Please map excel cell column before import"));
				}else{
					try{
						$excel_obj = \PhpOffice\PhpSpreadsheet\IOFactory::load($excel_file_path);
					}catch(Exception $e){
						die('Error loading file "' . pathinfo($excel_file_path, PATHINFO_BASENAME). '": ' . $e->getMessage());
						return json_encode(array('success' => false, 'message' => "Invalid file or path"));
					}
					$sheet           = $excel_obj->getSheet($excel_sheet_name);
					if($excel_row_end){
						$total_rows = $excel_row_end;
					}else{
						$total_rows = $sheet->getHighestRow();
					}
					$excel_exist_check_arr = $this->excel_exist_check_arr($sheet,$excel_row_start,$total_rows,$excel_format_result);
					$excel_wk_exist_arr    = count($excel_wk_exist_arr ?? []);
					$err_column_count      = count($excel_exist_check_arr['error'] ?? []);
					if((int)$err_column_count > 0){
						$table_info = $this->get_excel_error_ui($excel_exist_check_arr);
						echo json_encode(array('success'=>false,'message'=>"Date already exist",'table_info'=>$table_info));
						exit(0);
					}

					$employee_codes_arr = $this->get_excel_employee_codes($sheet,$excel_row_start,$total_rows,$excel_format_result,$module_id);
					$employee_count     = count($employee_codes_arr['employee_codes_arr'] ?? []); 
					$err_column_tabview = $employee_codes_arr['err_column_tabview'];

					if((int)$employee_count <= 0){
						echo json_encode(array('success'=>false,'message'=>"Please check Employee Code Column in your Excel Sheet.",'table_info'=>""));
						exit(0);
					}

					$err_column_tabview_count 	= count($err_column_tabview['error'] ?? []);
					if((int)$err_column_tabview_count > 0){
						$table_info = $this->get_excel_error_ui($err_column_tabview);
						echo json_encode(array('success'=>false,'message'=>"Resigned Employees data",'table_info'=>$table_info));
						exit(0);
					}

					$employee_codes     = trim(implode('","',$employee_codes_arr['employee_codes_arr'] ?? []));

	                //GET EMPLOYEE NAME FROM EMPLOYEE MASTER
					$emp_name_qry    = 'select employee_code,emp_name,date_of_joining from cw_employees where trans_status = 1 and employee_code in ("'.$employee_codes.'")';
					$emp_name_info   = $this->db->query("CALL sp_a_run ('RUN','$emp_name_qry')");
					$emp_name_result = $emp_name_info->result_array();
					$emp_name_info->next_result();

					// $emp_name_arr    = array();
					foreach($emp_name_result as $emp_key => $emp_val){
						$employee_code   = $emp_val['employee_code'];
						$emp_name_arr[$employee_code]   = $emp_val;

					}

					//GET SHIFT NAME FROM SHIFT MASTER
					$shift_name_qry     = 'select prime_shift_master_id,shift_name from cw_shift_master where trans_status = 1';
					$shift_name_info    = $this->db->query("CALL sp_a_run ('RUN','$shift_name_qry')");
					$shift_name_result  = $shift_name_info->result_array();
					$shift_name_info->next_result();

					$shift_name_arr     = array_reduce($shift_name_result, function ($result, $arr) {
					    $result[$arr['prime_shift_master_id']] = $arr['prime_shift_master_id'];
					    return $result;
					}, array());

					//SHIFT VALIDATION FOR MANUFACTURING - OPTIMIZED FOR BULK IMPORT
					if($this->config->item('MANUF') == 1){
						$add_col = ",shift_type";
						$add_ins = ',"M"';				
						$add_upd = ',shift_type = "MR"';	
						//Validate shift allowed - SINGLE QUERY BEFORE LOOP
						$shift_config_rslt = $this->shift_mapping($employee_code = "");	
						if($shift_config_rslt){
							$applicable_shift = $shift_config_rslt['applicable_shift'];
							$effective_date   = $shift_config_rslt['effective_date'];

							//Get first shift name from Excel to validate once
							$first_shift_name = "";
							foreach($sheet->getRowIterator() as $row){
								if($row->getRowIndex() >= $excel_row_start){
									$shift_cell = $this->get_excel_cell_value($sheet, $row, $excel_format_result, 'shift_name');
									if($shift_cell && $shift_cell != ""){
										$first_shift_name = $shift_cell;
										break;
									}
								}
							}

							if($first_shift_name){
								//Validate effective date once
								if($effective_date < $starting_date){
									echo json_encode(array('success'=>false,'message'=>"Effective date should be less than start date ($effective_date < $starting_date)"));
									exit(0);
								}

								//Validate shift applicability once
								if(!in_array($first_shift_name, explode(',', $applicable_shift))){
									echo json_encode(array('success'=>false,'message'=>"Shift not applicable for employees"));
									exit(0);
								}
							}

						}else{
							echo json_encode(array('success'=>false,'message'=>"shift config not mapped"));
							exit(0);
						}
					}

					//QUERY FOR CHECK EXIST DATA FROM TIME ENTRY TABLE 
					/*$time_entry_qry    = 'select employee_code,att_date from cw_time_entry where trans_status = 1 and cw_time_entry.employee_code in ("'.$employee_codes.'")';
					$time_entry_info   = $this->db->query("CALL sp_a_run ('RUN','$time_entry_qry')");
					$time_entry_result = $time_entry_info->result_array();
					$time_entry_info->next_result();

					// $time_entry_arr    = array_reduce($time_entry_result, function ($result, $arr) {
					// 	$result[$arr['employee_code']][$arr['att_date']] = $arr['att_date'];
					// 	return $result;
					// }, array());

					// $time_entry_arr        = array();
					foreach($time_entry_result as $time_key => $time_val){
						$time_emp_code     =  $time_val['employee_code'];
						$att_date          =  $time_val['att_date'];
						$time_entry_arr[$time_emp_code][$att_date]  = $att_date;
					}*/

					//------------- DON'T DELETE FOR LEAVE EXIST VALIDATION ----------
					//QUERY FOR CHECK EXIST DATA FROM LEAVE ENTRY TABLE 
					/*$leave_entry_qry    = 'select employee_code,leave_date from cw_leave_entry where trans_status = 1 and leave_status NOT IN (3,4) and financial_setting_id = "'.$prime_financial_id.'" and cw_leave_entry.employee_code in ("'.$employee_codes.'")';
					$leave_entry_info   = $this->db->query("CALL sp_a_run ('RUN','$leave_entry_qry')");
					$leave_entry_result = $leave_entry_info->result_array();
					$leave_entry_info->next_result();

					// $leave_entry_arr    = array();
					foreach($leave_entry_result as $leave_key => $leave_val){
						$leave_emp_code =  $leave_val['employee_code'];
						$leave_date     =  $leave_val['leave_date'];
						$leave_entry_arr[$leave_emp_code][$leave_date]  = $leave_date;
					}*/
					//------------- DON'T DELETE FOR LEAVE EXIST VALIDATION ----------

					//QUERY FOR CHECK EXIST DATA FROM ON DUTY ENTRY TABLE 
					$on_duty_entry_qry    = 'select employee_code,on_duty_date from cw_on_duty_entry where trans_status = 1 and on_duty_status NOT IN (3,4) and financial_setting_id = "'.$prime_financial_id.'" and cw_on_duty_entry.employee_code in ("'.$employee_codes.'")';
					$on_duty_entry_info   = $this->db->query("CALL sp_a_run ('RUN','$on_duty_entry_qry')");
					$on_duty_entry_result = $on_duty_entry_info->result_array();
					$on_duty_entry_info->next_result();

					$on_duty_entry_arr    = array();
					foreach($on_duty_entry_result as $on_duty_key => $on_duty_val){
						$on_duty_emp_code = $on_duty_val['employee_code'];
						$on_duty_date     = $on_duty_val['on_duty_date'];
						$on_duty_entry_arr[$on_duty_emp_code][$on_duty_date]  = $on_duty_date;
					}
					
					//QUERY FOR CHECK EXIST DATA FROM PERMISSION ENTRY TABLE 
					$permission_entry_qry    = 'select employee_code,permission_date from cw_permission_entry where trans_status = 1 and leave_status NOT IN (3,4) and financial_setting_id = "'.$prime_financial_id.'" and cw_permission_entry.employee_code in ("'.$employee_codes.'")';
					$permission_entry_info   = $this->db->query("CALL sp_a_run ('RUN','$permission_entry_qry')");
					$permission_entry_result = $permission_entry_info->result_array();
					$permission_entry_info->next_result();

					// $permission_entry_arr    = array();
					foreach($permission_entry_result as $permission_key => $permission_val){
						$permission_emp_code =  $permission_val['employee_code'];
						$permission_date     =  $permission_val['permission_date'];
						$permission_entry_arr[$permission_emp_code][$permission_date]  = $permission_date;
					}

					//QUERY FOR CHECK EXIST DATA FROM MANUAL PUNCH ENTRY TABLE 
					$mp_entry_qry         = 'select employee_code,shift_date from cw_manual_punch_entry where trans_status = 1 and leave_status NOT IN (3,4) and financial_setting_id = "'.$prime_financial_id.'" and cw_manual_punch_entry.employee_code in ("'.$employee_codes.'")';
					$mp_entry_info        = $this->db->query("CALL sp_a_run ('RUN','$mp_entry_qry')");
					$mp_entry_result      = $mp_entry_info->result_array();
					$mp_entry_info->next_result();

					// $mp_entry_arr            = array();
					foreach($mp_entry_result as $mp_entry_key => $mp_entry_val){
						$mp_entry_emp_code   =  $mp_entry_val['employee_code'];
						$mp_entry_date       =  $mp_entry_val['shift_date'];
						$mp_entry_arr[$mp_entry_emp_code][$mp_entry_date]  = $mp_entry_date;
					}

					//OVERTIME ENTRY EXIST CHECK
					$ot_entry_qry         = 'select employee_code,entry_date from cw_overtime_entry where trans_status = 1 and approval_status NOT IN (3,4) and financial_setting_id = "'.$prime_financial_id.'" and cw_overtime_entry.employee_code in ("'.$employee_codes.'")';
					$ot_entry_info        = $this->db->query("CALL sp_a_run ('RUN','$ot_entry_qry')");
					$ot_entry_result      = $ot_entry_info->result_array();
					$ot_entry_info->next_result();
					
					// $ot_entry_arr         = array();
					foreach($ot_entry_result as $ot_entry_key => $ot_entry_val){
						$ot_entry_emp_code   = $ot_entry_val['employee_code'];
						$ot_entry_date       = $ot_entry_val['entry_date'];
						$ot_entry_arr[$ot_entry_emp_code][$ot_entry_date]  = $ot_entry_date;
					}

					//SHIFT NAME EXIST CHECK QUERY
					//Check pending shift change request exist from request module
					$shift_request_qry    = 'SELECT employee_code,shift_date FROM cw_request WHERE cw_request.trans_status = 1 and cw_request.request_type = "6" and cw_request.leave_status in (1) and cw_request.financial_setting_id = "'.$prime_financial_id.'" and  cw_request.employee_code in ("'.$employee_codes.'")';
					// cw_request.leave_status in (1,2)
					$shift_request_info   = $this->db->query("CALL sp_a_run ('SELECT','$shift_request_qry')");
					$shift_request_rslt   = $shift_request_info->result_array();
					$shift_request_info->next_result();	

					$shift_request_arr    = array();
					foreach($shift_request_rslt as $shift_req_key => $shift_req_val){
						$shift_req_emp_code   = $shift_req_val['employee_code'];
						$shift_req_date       = $shift_req_val['shift_date'];
						$shift_request_arr[$shift_req_emp_code][$shift_req_date]  = $shift_req_date;
					}

					$highest_column       = $sheet->getHighestColumn();
					$worksheetTitle       = $sheet->getTitle();
					$status_array	      = array();
					$leave_creation_arr   = array();
					$opening_used_arr     = array();
					$opening_arr	      = array();
					$prime_query_value    = "";
					$prime_upd_value      = "";
					
					for($row =$excel_row_start; $row <= $total_rows; $row++) {
						$prime_column_val = "";
						$prime_cell_val   = "";
						$exist_val        = "";
						$status_info      = array();
						$status_info["Excel Row"] = $row;
						$sts              = TRUE;
						$email_sts        = TRUE;
						$picklist_sts     = TRUE;
						$exist_count      = 0;
						foreach($excel_format_result as $excel_info){
							$field_isdefault        = (int)$excel_info->field_isdefault;
							$mandatory_field        = (int)$excel_info->mandatory_field;
							$field_type             = (int)$excel_info->field_type;
							$pick_table             = $excel_info->pick_table;
							$pick_list_type         = (int)$excel_info->pick_list_type;
							$pick_list_import       = (int)$excel_info->pick_list_import;
							$pick_list              = $excel_info->pick_list;
							$excel_line_column_name = $excel_info->excel_line_column_name;
							$excel_line_value       = $excel_info->excel_line_value;

							$get_cell_value         = ucwords(trim($sheet->getCell("$excel_line_value$row")->getValue()));
                            if($get_cell_value){
								if($field_type === 12){
									//FOR EMAIL
									$email = $get_cell_value;
									if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
										$email_sts = FALSE;
									}
								}else
								if($field_type === 4){
									$excel_date     = $sheet->getCell("$excel_line_value$row")->getValue();	
									$unix_date      = $this->unix_convertion($excel_date);
									$get_cell_value = gmdate("Y-m-d", $unix_date);
									if($unix_date <= 0){
										$err_column_array['error']["$excel_line_value$row"] = "Please enter valid date... Please map The Date Format Like (DD/MM/YYYY)";
									}else
									if(($starting_date > $get_cell_value) || ($ending_date < $get_cell_value)){
										$err_column_array['error']["$excel_line_value$row"]   = "Date Should be inbetween Leave Financial Start date and End date..!..!";
									}
								}else
								if($field_type === 13){
									$get_cell_value = trim(date('Y-m-d H:i:s',Date::PHPToExcel($sheet->getCell("$excel_line_value$row")->getValue())));
								}else
								// FOR PICKLIST CHECK
								if(($field_type === 5) || ($field_type === 7)){
									if($pick_list_type === 1){
										$pick_list_val   = explode(",",$pick_list);
										$pick_list_val_1 = $pick_list_val[0];
										$pick_list_val_2 = $pick_list_val[1];
										$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'" and '.$pick_table.'.trans_status = 1';
										if($pick_list_import === 1){
											$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_1.' = "'.$get_cell_value.'" and '.$pick_table.'.trans_status = 1';	
										}else{
											$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'" and '.$pick_table.'.trans_status = 1';
										}	
										$pick_data  = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
										$pick_result = $pick_data->result();
										$pick_count  = $pick_data->num_rows();
										$pick_data->next_result();
										if((int)$pick_count === 0){
											$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
										}else
										if((int)$pick_count === 1){
											if($pick_table !== $this->prime_table){
												$pick_id     = $pick_result[0]->$pick_list_val_1;
												$pick_status = (int)$pick_result[0]->trans_status;
												if($pick_status === 0){
													$upd_query  = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = '.$pick_id;
													$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
												}
												$get_cell_value = $pick_id;
											}
										}
									}else
									if($pick_list_type === 2){
										$pick_list_val_1 = $pick_table."_id";
										$pick_list_val_2 = $pick_table."_value";
										$pick_list_val_3 = $pick_table."_status";
										$pick_query = 'select * from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'" and '.$pick_table.'.trans_status = 1';
										$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
										$pick_result = $pick_data->result();
										$pick_count  = $pick_data->num_rows();
										$pick_data->next_result();
										if((int)$pick_count === 0){
											$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
										}else
										if((int)$pick_count === 1){
											$pick_id     = $pick_result[0]->$pick_list_val_1;
											$pick_status = (int)$pick_result[0]->$pick_list_val_3;
											if($pick_status === 0){
												$upd_query  = 'update '.$pick_table.' set '.$pick_list_val_3.' = 1 where '.$pick_list_val_1.' = '.$pick_id;
												$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
											}
											$get_cell_value = $pick_id;
										}
									}
								}
								if($field_isdefault === 1){
									if($excel_line_column_name === 'employee_code'){
										$emp_code_col_name    = $excel_line_value;
										$employee_code        = $get_cell_value;
										$employee_name        = $emp_name_arr[$employee_code]['emp_name'];
										$check_emp_code       = $emp_name_arr[$employee_code]['employee_code'];
										
										//GET EMLOYEE DATE OF JOINING
										$emp_doj              = $emp_name_arr[$employee_code]['date_of_joining'];
										if(!$check_emp_code){
											$err_column_array['error']["$excel_line_value$row"] = "Employee Code ($employee_code) not Present in the Employee Master? Please Check it.!";
										}
									}else
									if($excel_line_column_name === 'shift_name'){
										$shift_name_col_name  = $excel_line_value;
										$shift_name           = $get_cell_value;
									}else
									if($excel_line_column_name === "from_date"){
										$from_date     = $get_cell_value;
									}else
									if($excel_line_column_name === "to_date"){
										$to_date       = $get_cell_value;
										$after_to_date = date('Y-m-d',strtotime("+1 day",strtotime($to_date)));
									}									
									if(empty($exist_column_name)){
										 if($mandatory_field === 1){
											$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
										}
									}else{
										if(in_array($excel_line_column_name,$exist_column_name)){
											$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
										}
									}
								}
							}
						}
						if($employee_code && $from_date && $to_date && $shift_name){
							//QUERY FOR CHECK EXIST DATA FROM SHIFT IMPORT TABLE 
							$shift_import_exist_qry  = 'select employee_code,shift_date,prime_shift_import_id as prime_id from cw_shift_import where trans_status = 1 and cw_shift_import.employee_code = "'.$employee_code.'" and shift_date between "'.$from_date.'" and "'.$to_date.'" and financial_setting_id ="'.$prime_financial_id.'"';
							$shift_import_exist_info = $this->db->query("CALL sp_a_run ('RUN','$shift_import_exist_qry')");
							$shift_import_exist_rslt = $shift_import_exist_info->result_array();
							$shift_import_exist_info->next_result();

							$shift_import_arr        = array();
							foreach($shift_import_exist_rslt as $shift_key => $shift_val){
								$shift_emp_code      =  $shift_val['employee_code'];
								$shift_date          =  $shift_val['shift_date'];
								$shift_import_arr[$shift_emp_code][$shift_date]  = $shift_val;
							}

							$period = new DatePeriod(
							    new DateTime("$from_date"),
							    new DateInterval('P1D'),
							    new DateTime("$after_to_date")
							);
							$exist_count       = 0;
							foreach ($period as $key => $value) {
								$shift_date         = $value->format('Y-m-d');
								$show_date          = $value->format('d-m-Y');
								$exist_date         = $shift_import_arr[$employee_code][$shift_date]['shift_date'];
								$prime_shift_id     = $shift_import_arr[$employee_code][$shift_date]['prime_id'];

								//CHECK A VALID SHIFT IMPORT OR NOT
								$check_shift_name   = $shift_name_arr[$shift_name];

								//CONDITION FOR CHECK A LEAVE ENTRY EXIST
								/*$check_leave        = $leave_entry_arr[$employee_code][$shift_date];*/

								//CONDITION FOR CHECK A ON DUTY ENTRY EXIST
								/*$check_on_duty      = $on_duty_entry_arr[$employee_code][$shift_date];*/

								//CONDITION FOR CHECK A PERMISSION ENTRY EXIST
								$check_permission    = $permission_entry_arr[$employee_code][$shift_date];

								//CONDITION FOR CHECK A MP ENTRY EXIST
								$check_man_punch     = $mp_entry_arr[$employee_code][$shift_date];

								//CONDITION FOR CHECK A OT ENTRY EXIST
								$check_ot            = $ot_entry_arr[$employee_code][$shift_date];

								//CONDITION FOR CHECK A PERMISSION ENTRY EXIST
								$shift_request_date  = $shift_request_arr[$employee_code][$shift_date];

								if($emp_doj > $shift_date){
									(int)$exist_count += 1;
									if($exist_count === 1){
										$err_column_array['error']["$excel_line_value$row"] = "Shift Date Should be Greater than Date of Joining Please Check it.!";
										$exist_count++;
									}
								}else
								if(!$check_shift_name){
									(int)$exist_count += 1;
									if($exist_count === 1){
										$err_column_array['error']["$excel_line_value$row"] = "Invalid Shift Name Please Check it.!";
										$exist_count++;
									}
								}else
								if($shift_request_date){
									(int)$exist_count += 1;
									if($exist_count === 1){
										$err_column_array['error']["$shift_date_col_name$row"] = "Date of $show_date Already Shift Request Pending? Please Check it.!";
										$exist_count++;
									}
								}
								/*else
								if($check_leave){
									(int)$exist_count += 1;
									if($exist_count === 1){
										$err_column_array['error']["$excel_line_value$row"] = "Date of $show_date Already Leave Request Created? Please Check it.!";
										$exist_count++;
									}
								}*/
								/*else
								if($check_on_duty){
									(int)$exist_count += 1;
									if($exist_count === 1){
										$err_column_array['error']["$excel_line_value$row"] = "Date of $show_date Already On Duty Request Created? Please Check it.!";
										$exist_count++;
									}
								}*/
								else
								if($check_permission){
									(int)$exist_count += 1;
									if($exist_count === 1){
										$err_column_array['error']["$excel_line_value$row"] = "Date of $show_date Already Permission Request Created? Please Check it.!";
										$exist_count++;
									}
								}else
								if($check_man_punch){
									(int)$exist_count += 1;
									if($exist_count === 1){
										$err_column_array['error']["$excel_line_value$row"] = "Date of $show_date Already Manual Punch Request Created? Please Check it.!";
										$exist_count++;
									}
								}else
								if($check_ot){
									(int)$exist_count += 1;
									if($exist_count === 1){
										$err_column_array['error']["$excel_line_value$row"] = "Date of $show_date Already Overtime Request Created? Please Check it.!";
										$exist_count++;
									}
								}else
								if($exist_date){
									//UPDATE QUERY VALUE
									$prime_upd_value .= '("'.$prime_shift_id.'","'.$employee_code.'","'.$employee_name.'","'.$from_date.'","'.$to_date.'","'.$shift_name.'","'.$shift_date.'","'.$prime_financial_id.'","'.$this->logged_id.'","'.$created_on.'"),';

									$status_info['Status'] = "Updated to DB";
									$status_array[] = $status_info;
								}else{
									//INSERT QUERY VALUE
									$prime_query_value .= '"'.$employee_code.'","'.$employee_name.'","'.$from_date.'","'.$to_date.'","'.$shift_name.'","'.$shift_date.'","'.$prime_financial_id.'","'.$this->logged_id.'","'.$created_on.'"),(';

									$status_info['Status'] = "Inserted to DB";
									$status_array[] = $status_info;
								}
							}
						}else{
							$err_column_array['error']["$emp_code_col_name$row"] = "Invalid Employee Data Imported? Please Check it..!";
						}
					}
					$err_column_count = count($err_column_array['error'] ?? []);
	
					if((int)$err_column_count > 0){
						$table_info   = $this->get_excel_error_ui($err_column_array);
						echo json_encode(array('success'=>false,'message'=>"Shift Details Not Imported",'table_info'=>$table_info));
					}else{
						//FOR SHIFT UPDATE
						if($prime_upd_value){
							$prime_upd_value        = rtrim($prime_upd_value,",");
							//TIME ENTRY UPD QUERY
							$shift_import_upd_qry   = 'INSERT INTO '.$this->prime_table.' (prime_shift_import_id,employee_code,employee_name,from_date,to_date,shift_name,shift_date,financial_setting_id,trans_updated_by,trans_updated_date'.$add_col.') VALUES '.$prime_upd_value.$add_upd.' ON DUPLICATE KEY UPDATE employee_code = VALUES(employee_code),employee_name = VALUES(employee_name),from_date = VALUES(from_date),to_date = VALUES(to_date),shift_name = VALUES(shift_name),shift_date = VALUES(shift_date),financial_setting_id = VALUES(financial_setting_id),trans_updated_by = VALUES(trans_updated_by),trans_updated_date = VALUES(trans_updated_date)'.$add_upd;
							$shift_import_upd_info  = $this->db->query($shift_import_upd_qry);

						}
						//FOR SHIFT INSERT
						if($prime_query_value){
							$prime_query_value      = rtrim($prime_query_value,"),(");
							$prime_column_val       = "employee_code,employee_name,from_date,to_date,shift_name,shift_date,financial_setting_id,trans_created_by,trans_created_date".$add_col;
							
							$prime_query            = "insert into $this->prime_table ($prime_column_val) VALUES ($prime_query_value)".$add_ins;						
							$insert_info            = $this->db->query($prime_query);
						}

						$table_info    = $this->get_excel_import_ui($status_array);
						return json_encode(array('success'=>true,'message'=>"Shift Details Updated.! Kindly reprocess Time Entry.!",'table_info'=>$table_info));
					}
				}
			}
		}
	}

	//import validation and checking updated
	public function do_excel_weekoff_import($import_id){
		$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;
		$starting_date         = date('Y-m-d',strtotime($leave_financial_info[0]->starting_date));	
		$ending_date           = date('Y-m-d',strtotime($leave_financial_info[0]->ending_date));	
		$emp_name_arr          = array();
		$holiday_exist_arr     = array();
		$time_entry_arr        = array();
		$leave_entry_arr       = array();
		$permission_entry_arr  = array();
		$on_duty_entry_arr     = array();
		$shift_import_arr      = array(); 
		$weekoff_import_arr    = array();
		$weekoff_id_arr        = array();
		$filename              = dirname(__FILE__)."/php_excel/PHPExcel/IOFactory.php";
		include($filename);
		if($import_id < 0){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}		
		$excel_path_qry    = 'select * from cw_import where import_id = "'.$import_id.'"';
		$excel_path_info   = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
		$excel_path_result = $excel_path_info->result();
		$excel_path_info->next_result();
		
		if(!$excel_path_result){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}else{
			$excel_file_path    = $excel_path_result[0]->excel_file_path;
			$module_id          = $excel_path_result[0]->module_id;
			$excel_format       = $excel_path_result[0]->excel_format;
			$excel_sheet_name   = (int)$excel_path_result[0]->excel_sheet_name;
			$excel_row_start    = (int)$excel_path_result[0]->excel_start_row;
			$excel_row_end      = (int)$excel_path_result[0]->excel_end_row;
			
			$format_qry 	= 'select * from cw_util_excel_format where prime_excel_format_id = "'.$excel_format.'" and cw_util_excel_format.trans_status = 1';
			$format_info    = $this->db->query("CALL sp_a_run ('SELECT','$format_qry')");
			$format_rslt    = $format_info->result();
			$format_info->next_result();
			
			if(!$format_rslt){
				return json_encode(array('success' => false, 'message' => "Please add excel format before import"));
			}else{
				$exist_column_name   = explode(",",$format_rslt[0]->exist_column_name);
				$excel_format_qry 	 = 'select field_type,pick_table,pick_list_type,pick_list_import,pick_list,mandatory_field,field_isdefault,excel_line_column_name,excel_line_value from cw_util_excel_format_line inner join cw_form_setting on label_name = excel_line_column_name where excel_line_module_id = "'.$module_id.'" and prime_excel_format_id = "'.$excel_format.'" and cw_form_setting.prime_module_id = "'.$module_id.'" and cw_util_excel_format_line.trans_status = 1';			
				$excel_format        = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
				$excel_format_result = $excel_format->result();
				$excel_format->next_result();

				if(!$excel_format_result){
					return json_encode(array('success' => false, 'message' => "Please map excel cell column before import"));
				}else{
					try{
						$excel_obj = \PhpOffice\PhpSpreadsheet\IOFactory::load($excel_file_path);
					}catch(Exception $e){
						die('Error loading file "' . pathinfo($excel_file_path, PATHINFO_BASENAME). '": ' . $e->getMessage());
						return json_encode(array('success' => false, 'message' => "Invalid file or path"));
					}
					$sheet          = $excel_obj->getSheet($excel_sheet_name);
					if($excel_row_end){
						$total_rows = $excel_row_end;
					}else{
						$total_rows = $sheet->getHighestRow();
					}
					
					$excel_exist_check_arr = $this->excel_exist_check_arr($sheet,$excel_row_start,$total_rows,$excel_format_result);
					$excel_wk_exist_arr    = count($excel_wk_exist_arr ?? []); 
					$err_column_count 	   = count($excel_exist_check_arr['error'] ?? []);
					if((int)$err_column_count > 0){
						$table_info = $this->get_excel_error_ui($excel_exist_check_arr);
						echo json_encode(array('success'=>false,'message'=>"Date already exist",'table_info'=>$table_info));
						exit(0);
					}

					$employee_codes_arr = $this->get_excel_employee_codes($sheet,$excel_row_start,$total_rows,$excel_format_result,$module_id);
					$employee_count = count($employee_codes_arr['employee_codes_arr'] ?? []); 
					$err_column_tabview = $employee_codes_arr['err_column_tabview'];
					$err_column_tabview_count 	= count($err_column_tabview['error'] ?? []);
					if((int)$err_column_tabview_count > 0){
						$table_info = $this->get_excel_error_ui($err_column_tabview);
						echo json_encode(array('success'=>false,'message'=>"Resigned Employees data",'table_info'=>$table_info));
						exit(0);
					}

					if((int)$employee_count <= 0){
						echo json_encode(array('success'=>false,'message'=>"Please check Employee Code Column in your Excel Sheet.!",'table_info'=>""));
						exit(0);
					}

					//for holiday start
					$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();	
				
					$holy_label_name        = $holid_component_result[0]->label_name;
					$emp_holy_label         = "";
					if($holy_label_name){
						$emp_holy_label     = ",$holy_label_name";
					}

					$holiday_qry       = 'select cw_holiday_entry_holiday_data.holiday_date,component_value from cw_holiday_entry_holiday_data where cw_holiday_entry_holiday_data.holiday_date >= "'.$starting_date.'" and cw_holiday_entry_holiday_data.holiday_date <= "'.$ending_date.'" 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_exist_arr     = array();
					foreach($holiday_result as $holy_key => $holy_val){
						$holy_date                        = $holy_val['holiday_date'];
						$holy_comp_value                  = $holy_val['component_value'];
						$holiday_exist_arr[$holy_date]    = $holy_comp_value;
						// $holiday_exist_arr[$holy_date]    = $holy_val;
					}
					//for holiday end

					$employee_codes    = trim(implode('","',$employee_codes_arr['employee_codes_arr'] ?? []));

					//GET EMPLOYEE NAME FROM EMPLOYEE MASTER
					$emp_name_qry      = 'select employee_code,emp_name,date_of_joining'.$emp_holy_label.' from cw_employees where trans_status = 1 and employee_code in ("'.$employee_codes.'")';
					$emp_name_info     = $this->db->query("CALL sp_a_run ('RUN','$emp_name_qry')");
					$emp_name_result   = $emp_name_info->result_array();
					$emp_name_info->next_result();

					// $emp_name_arr      = array();
					foreach($emp_name_result as $emp_key => $emp_val){
						$employee_code                  = $emp_val['employee_code'];
						$emp_name_arr[$employee_code]   = $emp_val;
					}
					
					//QUERY FOR CHECK EXIST DATA FROM TIME ENTRY TABLE 
					/*$time_entry_qry    = 'select employee_code,att_date from cw_time_entry where trans_status = 1 and cw_time_entry.employee_code in ("'.$employee_codes.'")';
					// and whole_day_status in ("L","W","H")
					$time_entry_info   = $this->db->query("CALL sp_a_run ('RUN','$time_entry_qry')");
					$time_entry_result = $time_entry_info->result_array();
					$time_entry_info->next_result();

					$time_entry_arr    = array();
					foreach($time_entry_result as $time_key => $time_val){
						$time_emp_code   = $time_val['employee_code'];
						$time_att_date   = $time_val['att_date'];
						$time_entry_arr[$time_emp_code][$time_att_date]   = $time_att_date;
					}*/

					//QUERY FOR CHECK EXIST DATA FROM LEAVE ENTRY TABLE 
					$leave_entry_qry    = 'select employee_code,leave_date from cw_leave_entry where trans_status = 1 and leave_status NOT IN (3,4) and financial_setting_id = "'.$prime_financial_id.'" and cw_leave_entry.employee_code in ("'.$employee_codes.'")';
					$leave_entry_info   = $this->db->query("CALL sp_a_run ('RUN','$leave_entry_qry')");
					$leave_entry_result = $leave_entry_info->result_array();
					$leave_entry_info->next_result();

					// $leave_entry_arr    = array();
					foreach($leave_entry_result as $leave_key => $leave_val){
						$leave_emp_code   = $leave_val['employee_code'];
						$leave_date       = $leave_val['leave_date'];
						$leave_entry_arr[$leave_emp_code][$leave_date]   = $leave_date;
					}
					
					//QUERY FOR CHECK EXIST DATA FROM PERMISSION ENTRY TABLE 
					$permission_entry_qry    = 'select employee_code,permission_date from cw_permission_entry where trans_status = 1 and leave_status NOT IN (3,4) and financial_setting_id = "'.$prime_financial_id.'" and cw_permission_entry.employee_code in ("'.$employee_codes.'")';
					$permission_entry_info   = $this->db->query("CALL sp_a_run ('RUN','$permission_entry_qry')");
					$permission_entry_result = $permission_entry_info->result_array();
					$permission_entry_info->next_result();

					// $permission_entry_arr    = array();
					foreach($permission_entry_result as $per_key => $per_val){
						$per_emp_code        = $per_val['employee_code'];
						$permission_date     = $per_val['permission_date'];
						$permission_entry_arr[$per_emp_code][$permission_date]   = $permission_date;
					}

					//QUERY FOR CHECK EXIST DATA FROM ON DUTY ENTRY TABLE 
					/*$on_duty_entry_qry    = 'select employee_code,on_duty_date from cw_on_duty_entry where trans_status = 1 and on_duty_status NOT IN (3,4) and financial_setting_id = "'.$prime_financial_id.'" and cw_on_duty_entry.employee_code in ("'.$employee_codes.'")';
					$on_duty_entry_info   = $this->db->query("CALL sp_a_run ('RUN','$on_duty_entry_qry')");
					$on_duty_entry_result = $on_duty_entry_info->result_array();
					$on_duty_entry_info->next_result();

					$on_duty_entry_arr    = array();
					foreach($on_duty_entry_result as $od_key => $od_val){
						$od_emp_code      = $od_val['employee_code'];
						$od_date          = $od_val['on_duty_date'];
						$on_duty_entry_arr[$od_emp_code][$od_date]   = $od_date;
					}*/

					//QUERY FOR CHECK EXIST DATA FROM WEEKOFF IMPORT TABLE 
					$weekoff_import_exist_qry    = 'select prime_weekoff_import_id,employee_code,weekoff_date,weekoff_type from cw_weekoff_import where trans_status = 1 and financial_setting_id = "'.$prime_financial_id.'" and employee_code in ("'.$employee_codes.'")';
					$weekoff_import_exist_info   = $this->db->query("CALL sp_a_run ('RUN','$weekoff_import_exist_qry')");
					$weekoff_import_exist_result = $weekoff_import_exist_info->result_array();
					$weekoff_import_exist_info->next_result();
					
					// $weekoff_id_arr        = array();
					// $weekoff_import_arr    = array();
					foreach($weekoff_import_exist_result as $weekoff_key => $weekoff_val){
						$weekoff_emp_code  = $weekoff_val['employee_code'];
						$weekoff_date      = $weekoff_val['weekoff_date'];
						$weekoff_type      = $weekoff_val['weekoff_type'];
						$weekoff_id        = $weekoff_val['prime_weekoff_import_id'];
						// $weekoff_id_arr[$weekoff_emp_code][$weekoff_date]      = $weekoff_id;
						// $weekoff_import_arr[$weekoff_emp_code][$weekoff_date]  = $weekoff_type;
						$weekoff_import_arr[$weekoff_emp_code][$weekoff_date]  = $weekoff_val;
					}
					
					$highest_column          = $sheet->getHighestColumn();
					$worksheetTitle          = $sheet->getTitle();
					$status_array	         = array();
					$leave_creation_arr      = array();
					$opening_used_arr        = array();
					$opening_arr	         = array(); 
					$weekoff_excel_exist_arr = array();
					$prime_query_value       = "";
					$prime_upd_query_value   = "";

					for($row =$excel_row_start; $row <= $total_rows; $row++) {
						$prime_column_val         = "";
						$prime_cell_val           = "";
						$exist_val                = "";
						$status_info              = array();
						$status_info["Excel Row"] = $row;
						$sts                      = TRUE;
						$email_sts                = TRUE;
						foreach($excel_format_result as $excel_info){
							$field_isdefault        = (int)$excel_info->field_isdefault;
							$mandatory_field        = (int)$excel_info->mandatory_field;
							$field_type             = (int)$excel_info->field_type;
							$pick_table             = $excel_info->pick_table;
							$pick_list_type         = (int)$excel_info->pick_list_type;
							$pick_list_import       = (int)$excel_info->pick_list_import;
							$pick_list              = $excel_info->pick_list;
							$excel_line_column_name = $excel_info->excel_line_column_name;
							$excel_line_value       = $excel_info->excel_line_value;

							$get_cell_value         = ucwords(trim($sheet->getCell("$excel_line_value$row")->getValue()));
							if($get_cell_value){
								//FOR MOBILE NUMBER
								if($field_type === 11){
									$length = strlen($get_cell_value);
									$length_query = 'select field_length from cw_form_setting where cw_form_setting.prime_module_id = "'.$module_id.'" and cw_form_setting.field_type = 11';
									$length_data  = $this->db->query("CALL sp_a_run ('SELECT','$length_query')");
									$length_result = $length_data->result();
									$length_data->next_result();
									$field_length = $length_result[0]->field_length;
									if($field_length != $length){
										$sts = FALSE;
									}
								}else 
								if($field_type === 12){
									//FOR EMAIL
									$email = $get_cell_value;
									if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
										$email_sts = FALSE;
									}
								}else
								if($field_type === 4){
									// FOR DATE
									$get_cell_value = trim(Date::excelToDateTimeObject((int)$sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));
									$format         = "Y-m-d";

									$date = DateTime::createFromFormat($format , $get_cell_value);

									$date_format_sts  = $date && $date->format($format) === $get_cell_value;
									if(!$date_format_sts){
										$err_column_array['error']["$excel_line_value$row"]   = "Invalid Date Format.!Please Map Date Format like (DD/MM/YYYY).!";
									}else
									if(($starting_date > $get_cell_value) || ($ending_date < $get_cell_value)){
										$err_column_array['error']["$excel_line_value$row"]   = "Date Should add between Leave Financial Start Date and End Date.!";
									}
								}else
								if($field_type === 13){
									$get_cell_value = trim(date('Y-m-d H:i:s',Date::PHPToExcel($sheet->getCell("$excel_line_value$row")->getValue())));
								}else
								// FOR PICKLIST CHECK
								if(($field_type === 5) || ($field_type === 7)){
									if($pick_list_type === 1){
										$pick_list_val   = explode(",",$pick_list);
										$pick_list_val_1 = $pick_list_val[0];
										$pick_list_val_2 = $pick_list_val[1];
										$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
										if($pick_list_import === 1){
											$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_1.' = "'.$get_cell_value.'"';	
										}else{
											$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
										}	
										$pick_data  = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
										$pick_result = $pick_data->result();
										$pick_count  = $pick_data->num_rows();
										$pick_data->next_result();
										if((int)$pick_count === 0){
											$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
										}else
										if((int)$pick_count === 1){
											if($pick_table !== $this->prime_table){
												$pick_id     = $pick_result[0]->$pick_list_val_1;
												$pick_status = (int)$pick_result[0]->trans_status;
												if($pick_status === 0){
													$upd_query  = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = '.$pick_id;
													$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
												}
												$get_cell_value = $pick_id;
											}
										}
									}else
									if($pick_list_type === 2){
										$pick_list_val_1 = $pick_table."_id";
										$pick_list_val_2 = $pick_table."_value";
										$pick_list_val_3 = $pick_table."_status";
										$pick_query = 'select * from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
										$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
										$pick_result = $pick_data->result();
										$pick_count  = $pick_data->num_rows();
										$pick_data->next_result();
										if((int)$pick_count === 0){
											$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
										}else
										if((int)$pick_count === 1){
											$pick_id     = $pick_result[0]->$pick_list_val_1;
											$pick_status = (int)$pick_result[0]->$pick_list_val_3;
											if($pick_status === 0){
												$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
											}
											$get_cell_value = $pick_id;
										}
									}
								}
								if($field_isdefault === 1){
									if($excel_line_column_name === 'employee_code'){
										$emp_code_col_name  = $excel_line_value;
										$employee_code      = $get_cell_value;
										$employee_name      = $emp_name_arr[$employee_code]['emp_name'];
										$check_emp_code     = $emp_name_arr[$employee_code]['employee_code'];
										//GET EMPLOYEE DATE OF JOINING
										$emp_doj            = $emp_name_arr[$employee_code]['date_of_joining'];
										if(!$check_emp_code){
											$err_column_array['error']["$excel_line_value$row"] = "Employee Code ($employee_code) not Present in the Employee Master? Please Check it.!";
										}
									}else
									if($excel_line_column_name === "from_date"){
										$from_date         = $get_cell_value;
									}else
									if($excel_line_column_name === "to_date"){
										$to_date           = $get_cell_value;
										$after_to_date     = date('Y-m-d',strtotime("+1 day",strtotime($to_date)));
									}else
									if($excel_line_column_name === 'weekoff_type'){
										$shift_name_col_name  = $excel_line_value;
										$weekoff_type         = (int)$get_cell_value;
									}								
									if(empty($exist_column_name)){
										if($mandatory_field === 1){
											$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
										}
									}else{
										if(in_array($excel_line_column_name,$exist_column_name)){
											$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
										}
									}
								}
							}
						}
						if($employee_code && $employee_name && $from_date && $to_date && $weekoff_type){
							$period = new DatePeriod(
								new DateTime("$from_date"),
								new DateInterval('P1D'),
								new DateTime("$after_to_date")
							);
						}
						$exist_count       = 0;
						foreach ($period as $key => $value) {
							$weekoff_date           = $value->format('Y-m-d');
							$dis_week_date          = $value->format('d-m-Y');

							//CHECK A VALID WEEKOFF TYPE FOR TO IMPORT OR NOT
							// $check_weekoff_type     = (int)$weekoff_import_arr[$employee_code][$weekoff_date];
							// $weekoff_id             = $weekoff_id_arr[$employee_code][$weekoff_date];
							$check_weekoff_type     = (int)$weekoff_import_arr[$employee_code][$weekoff_date]['weekoff_type'];
							$weekoff_id             = $weekoff_import_arr[$employee_code][$weekoff_date]['prime_weekoff_import_id'];

							// CHECK A TIME ENTRY EXIST
							// $check_time_entry       = $time_entry_arr[$employee_code][$weekoff_date];

							// CHECK A LEAVE ENTRY EXIST
							$check_leave_entry      = $leave_entry_arr[$employee_code][$weekoff_date];

							// CHECK A ON DUTY ENTRY EXIST
							// $check_on_duty_entry    = $on_duty_entry_arr[$employee_code][$weekoff_date];

							// CHECK A PERMISSION ENTRY EXIST
							$check_permission_entry = $permission_entry_arr[$employee_code][$weekoff_date];

							//CHECK A HOLIDAY EXIST
							$holiday_exist_val      = $holiday_exist_arr[$weekoff_date];
							$holy_comp_arr          = array();
							
							// --------------------- VALIDATION CHECKING START ----------------------
							if($holiday_exist_val && $holy_label_name){
								$holy_emp_label     = $emp_name_arr[$employee_code][$holy_label_name];
								$holy_comp_arr      = explode(",",$holiday_exist_val);

								if(in_array($holy_emp_label,$holy_comp_arr)){
									(int)$exist_count += 1;
									if($exist_count === 1){
										$err_column_array['error']["$row"] = "Already Holiday added for this date of $dis_week_date";
										$exist_count++;
									}
								}
							}
							if($emp_doj > $weekoff_date){
								(int)$exist_count += 1;
								if($exist_count === 1){
									$err_column_array['error']["$row"] = "Weekoff Date Should be Greater than date of Joining Please Check it.!";
									$exist_count++;
								}
							}
							/*else
							if($check_time_entry){
								(int)$exist_count += 1;
								//IF CHECK COUNT === 1 FOR SAME EXCEL ROW(FROM AND TO DATE PERIOD)
								if($exist_count === 1){
									$err_column_array['error']["$row"] = "$employee_code Time Entry Exist in Date of $dis_week_date";
									$exist_count++;
								}
							}*/
							else
							if($check_leave_entry){
								(int)$exist_count += 1;
								//IF CHECK COUNT === 1 FOR SAME EXCEL ROW(FROM AND TO DATE PERIOD)
								if($exist_count === 1){
									$err_column_array['error']["$row"] = "$employee_code Leave Entry Exist in date of $dis_week_date";
									$exist_count++;
								}
							}
							/*else
							if($check_on_duty_entry){
								(int)$exist_count += 1;
								//IF CHECK COUNT === 1 FOR SAME EXCEL ROW(FROM AND TO DATE PERIOD)
								if($exist_count === 1){
									$err_column_array['error']["$row"] = "$employee_code On Duty Entry Exist in Date of $dis_week_date";
									$exist_count++;
								}
							}*/
							else
							if($check_permission_entry){
								(int)$exist_count += 1;
								//IF CHECK COUNT === 1 FOR SAME EXCEL ROW(FROM AND TO DATE PERIOD)
								if($exist_count === 1){
									$err_column_array['error']["$row"] = "$employee_code Permission Entry Exist in date of $dis_week_date";
									$exist_count++;
								}
							}else
							if($check_weekoff_type){
								if($check_weekoff_type === $weekoff_type || $check_weekoff_type === 1){
									(int)$exist_count += 1;
									if($exist_count === 1){
										$err_column_array['error']["$row"] = "$employee_code Already Weekoff Imported in date of $dis_week_date? Please Check Weekoff Import.!";
										$exist_count++;
									}
								}
								/*else
								if($weekoff_excel_exist_arr[$employee_code][$weekoff_date]){
									$err_column_array['error']["$row"] = "Duplicate data Exist for Date of $dis_week_date.! Please Check Your Excel?";
									$exist_count++;
								}*/
								else{
									$prime_upd_query_value .= '("'.$weekoff_id.'","'.$weekoff_type.'",'.'"'.$this->logged_id.'",'.'"'.date("Y-m-d H:i:s").'"),';

									$status_info['Status']   = "Updated to DB";
									$status_array[]          = $status_info;
									// $weekoff_excel_exist_arr = array([$employee_code][$weekoff_date]);
								}
							}else{
								$prime_query_value .= '"'.$employee_code.'","'.$employee_name.'","'.$from_date.'","'.$to_date.'","'.$weekoff_date.'","'.$weekoff_type.'","'.$prime_financial_id.'","'.$this->logged_id.'","'.$created_on.'"),(';
								
								$status_info['Status'] = "Inserted to DB";
								$status_array[] = $status_info;
							}
							// ----------------------- VALIDATION CHECKING END -----------------------	
						} 
					}
					$err_column_count = count($err_column_array['error'] ?? []);
					if((int)$err_column_count > 0){
						$table_info = $this->get_excel_error_ui($err_column_array);
						echo json_encode(array('success'=>false,'message'=>"Data Not Imported",'table_info'=>$table_info));

					}else{
						$rslt = false;
						if($prime_query_value){
							$prime_column_val = "employee_code,employee_name,from_date,to_date,weekoff_date,weekoff_type,financial_setting_id,trans_created_by,trans_created_date";
							$prime_query_value = rtrim($prime_query_value,"),(");	
							$prime_query   = "insert into $this->prime_table ($prime_column_val) VALUES ($prime_query_value)";						
							$insert_info   = $this->db->query($prime_query);
							$rslt = true;
						}
						//UPDATE A SHIFT NAME FOR SAME SHIFT DATE
						if($prime_upd_query_value){
							$prime_upd_query_value = rtrim($prime_upd_query_value,',');
							//MULTI UPDATE QUERY TO WEEKOFF IMPORT TABLE
							$upd_weekoff_qry     = 'INSERT INTO cw_weekoff_import (prime_weekoff_import_id,weekoff_type,trans_updated_by,trans_updated_date) VALUES '.$prime_upd_query_value.' ON DUPLICATE KEY UPDATE weekoff_type = VALUES(weekoff_type),trans_updated_by = VALUES(trans_updated_by),trans_updated_date = VALUES(trans_updated_date)'; 
							$this->db->query($upd_weekoff_qry);
							// $this->db->query("CALL sp_a_run ('UPDATE','$upd_weekoff_qry')");
							$rslt = true;
						}
						if($rslt){
							$table_info = $this->get_excel_import_ui($status_array);
							return json_encode(array('success'=>true,'message'=>"Successfully File Imported",'table_info'=>$table_info));
						}else{
							return json_encode(array('success'=>true,'message'=>" File Not Imported",'table_info'=>$table_info));
						}
					}
				}
			}
		}
	}
		
	//import validation and checking updated
	public function do_excel_leave_import($import_id){
		$leave_financial_info = $this->get_leave_financial_details();
		$prime_financial_id   = $leave_financial_info[0]->prime_leave_financial_year_id;
		$starting_date        = date('Y-m-d',strtotime($leave_financial_info[0]->starting_date));	
		$ending_date          = date('Y-m-d',strtotime($leave_financial_info[0]->ending_date));	
		if($import_id < 0){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}
		
		$excel_path_qry    = 'select * from cw_import where import_id = "'.$import_id.'"';
		$excel_path_info   = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
		$excel_path_result = $excel_path_info->result();
		$excel_path_info->next_result();
		if(!$excel_path_result){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}else{
			$excel_file_path    = $excel_path_result[0]->excel_file_path;
			$module_id          = $excel_path_result[0]->module_id;
			$excel_format       = $excel_path_result[0]->excel_format;
			$excel_sheet_name   = (int)$excel_path_result[0]->excel_sheet_name;
			$excel_row_start    = (int)$excel_path_result[0]->excel_start_row;
			$excel_row_end      = (int)$excel_path_result[0]->excel_end_row;
			
			$format_qry 	= 'select * from cw_util_excel_format where prime_excel_format_id = "'.$excel_format.'" and cw_util_excel_format.trans_status = 1';
			$format_info    = $this->db->query("CALL sp_a_run ('SELECT','$format_qry')");
			$format_rslt    = $format_info->result();
			$format_info->next_result();
			if(!$format_rslt){
				return json_encode(array('success' => false, 'message' => "Please add excel format before import"));
			}else{ 
				//$excel_row_start   = (int)$format_rslt[0]->excel_row_start;
				$exist_column_name  = explode(",",$format_rslt[0]->exist_column_name);
				$excel_format_qry 	= 'select field_type,pick_table,pick_list_type,pick_list_import,pick_list,mandatory_field,field_isdefault,excel_line_column_name,excel_line_value from cw_util_excel_format_line inner join cw_form_setting on label_name = excel_line_column_name where excel_line_module_id = "'.$module_id.'" and prime_excel_format_id = "'.$excel_format.'" and cw_form_setting.prime_module_id = "'.$module_id.'" and cw_util_excel_format_line.trans_status = 1 ORDER BY cw_util_excel_format_line.excel_line_value ASC';			
				$excel_format        = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
				$excel_format_result = $excel_format->result();
				$excel_format->next_result();
	
				if(!$excel_format_result){
					return json_encode(array('success' => false, 'message' => "Please map excel cell column before import"));
				}else{
					try{
						$excel_obj = \PhpOffice\PhpSpreadsheet\IOFactory::load($excel_file_path);
					}catch(Exception $e){
						die('Error loading file "' . pathinfo($excel_file_path, PATHINFO_BASENAME). '": ' . $e->getMessage());
						return json_encode(array('success' => false, 'message' => "Invalid file or path"));
					}
					$sheet           = $excel_obj->getSheet($excel_sheet_name);
					if($excel_row_end){
						$total_rows = $excel_row_end;
					}else{
						$total_rows = $sheet->getHighestRow();
					}
					$highest_column        = $sheet->getHighestColumn();
					$worksheetTitle        = $sheet->getTitle();
					$leave_creation_arr    = array();
					$opening_used_arr      = array();
					$opening_arr	       = array();
					$status_array	       = array();
					$err_status_array	   = array();
					$prime_query_value     = "";
					$time_entry_upd_value  = "";
					$time_entry_ins_value  = "";

					//get employee category from employees table
					$employees_qry       = 'select employee_code,role,date_of_joining from cw_employees where cw_employees.trans_status = 1 and termination_status = 0';
					$employees_qry_info  = $this->db->query("CALL sp_a_run ('SELECT','$employees_qry')");
					$employees_qry_rslt  = $employees_qry_info->result_array();
					$employees_qry_info->next_result();

					$employees_arr       = array();
					foreach($employees_qry_rslt as $emp_key => $emp_val){
						$emp_code                  = $emp_val['employee_code'];
						$employees_arr[$emp_code]  = $emp_val;
						$active_emp_arr[$emp_code] = $emp_code;
					}

					//Leave creation query for get a leave name
					$leave_creation_qry   = 'select prime_leave_creation_id,LOWER(leave_name) as leave_name,leave_opening from cw_leave_creation where cw_leave_creation.trans_status = 1';
					// and financial_setting_id = "'.$prime_financial_id.'"
					$leave_creation_info  = $this->db->query("CALL sp_a_run ('SELECT','$leave_creation_qry')");
					$leave_creation_rslt  = $leave_creation_info->result_array();
					$leave_creation_info->next_result();

					$leave_creation_arr   = array_reduce($leave_creation_rslt, function($result, $arr) {
				    $result[$arr['prime_leave_creation_id']] = $arr;
					    return $result;
					}, array());

					$leave_name_query     = $this->db->query("SELECT leave_name,leave_opening FROM cw_leave_creation WHERE trans_status = 1");
					$columns              = $leave_name_query->result();
					if(count($columns ?? []) === 0){
						return json_encode(array('success' => false, 'message' => "First You should Add a Leave Name in Leave Creation Module..!!"));
					}else{
						$leave_name_used  = "";
						foreach ($columns as $key => $value) {
							// $leave_name    =  strtolower($value->leave_name);
							$leave_name     = str_replace(" ","_",strtolower($value->leave_name));
							$leave_opening  = (int)$value->leave_opening;
							if($leave_opening === 1){
								if($leave_name){
									$leave_name_balance_used   .= ',(('.$leave_name.'+'.$leave_name.'_credit)-('.$leave_name.'_debit + used_'.$leave_name.'+ pending_'.$leave_name.')) as balance_'.$leave_name.',used_'.$leave_name;		
								}	
							}	
						}	
						if($leave_name_balance_used){
							//Get a balance and used count from leave opening table with leave
							$opening_balance_used_qry   = "SELECT employee_code".$leave_name_balance_used." from cw_leave_opening where cw_leave_opening.trans_status = 1 and financial_setting_id = '".$prime_financial_id."'";
							$opening_balance_used_data  = $this->db->query($opening_balance_used_qry);
							$opening_balance_used_rslt  = $opening_balance_used_data->result_array();

							$opening_balance_used_arr   = array();
							foreach($opening_balance_used_rslt as $key => $arr){
								$opening_balance_used_arr[$arr['employee_code']] = $arr;
							}
						}
						//GET LAST PAYROLL MONTH
						$last_payroll_month   = 'select max(date_format(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y") , "%Y-%m")) as max_month from cw_transactions where trans_status = 1';
						$last_payroll_info    = $this->db->query("CALL sp_a_run ('SELECT','$last_payroll_month')");
						$last_payroll_rslt    = $last_payroll_info->result();
						$last_payroll_info->next_result();
						$last_pay_month       = $last_payroll_rslt[0]->max_month;
						$nxt_month            = date("d-m-Y", strtotime($last_pay_month."-01"));
						if(!empty($last_pay_month)){
							$nxt_month = date("d-m-Y", strtotime($last_pay_month . "-01"));
						}else{
							$nxt_month = ''; // or set default like '01-01-1900'
						}
						//GET SALARY FROM DATE
						$month_day_result     = $this->tos_day_qry_fun("3");
						$day_start            = $month_day_result[0]->day_start;
						$day_end              = $month_day_result[0]->day_end;
						if(!$day_start || $day_start === ""){
							$day_start = "01";
						}
						$month_start_date     = date("Y-m",strtotime($nxt_month))."-".$day_start;
						

						//SELECT QUERY FOR GET DAY DESCRIPTION FOR CHECK VALIDATION IN TIME ENTRY TABLE
						$day_status_legend_qry  = 'select legends,day_description,day_type from cw_day_status_legends where cw_day_status_legends.trans_status = 1';
						$day_status_legend_info = $this->db->query("CALL sp_a_run ('SELECT','$day_status_legend_qry')");
						$day_status_legend_rslt = $day_status_legend_info->result_array();
						$day_status_legend_info->next_result();
						
						$day_status_legend_arr  = array_reduce($day_status_legend_rslt, function($result, $arr){
					    	$result[$arr['legends']] = $arr;
					    	return $result;
						}, array());

						$time_entry_sel_qry     = 'select * from cw_time_entry where att_date >= "'.$month_start_date.'" and trans_status = 1';
						$time_entry_info        = $this->db->query("CALL sp_a_run ('SELECT','$time_entry_sel_qry')");
						$time_entry_rslt        = $time_entry_info->result_array();
						$time_entry_info->next_result();
						foreach($time_entry_rslt as $key => $val){
							$time_entry_data_arr[$val['employee_code']][$val['att_date']]=$val;
						}

						$leave_creation_qry     = 'select * from cw_leave_creation where trans_status=1 and leave_opening = 1';
						$leave_creation_info    = $this->db->query("CALL sp_a_run ('SELECT','$leave_creation_qry')");
						$leave_creation_rslt    = $leave_creation_info->result_array();
						$leave_creation_info->next_result();
						$leave_name_arr         = array_column($leave_creation_rslt,"prime_leave_creation_id","leave_name");
						$fh_check_arr           = array("LP","LW","LU","LI","OW","MW","MI","OP");
						$sh_check_arr           = array("PL","WL","UL","IL","WO","WM","IM","PO");
						$common_check_sts       = array("W","P","U","H");

						// For duplicate checking Bases on leave entry & on duty.
						$validate_arr           = $this->build_common_valid_array();	
						//get current financial year details
						$leave_financial_info   = $this->get_leave_financial_details();
						$prime_financial_id     =  $leave_financial_info[0]->prime_leave_financial_year_id;	
						$starting_date          = date('Y-m-d',strtotime($leave_financial_info[0]->starting_date));	
						$ending_date            = date('Y-m-d',strtotime($leave_financial_info[0]->ending_date));	
						$error                  = 0;
						// $success_sts     = array();
						$min_leave_date                  = "0000-00-00";
						$max_leave_date                  = "0000-00-00";
						$approved_arr           = [];
						for($row = $excel_row_start; $row <= $total_rows; $row++){
							$prime_column_val             = "";
							$prime_cell_val               = "";
							$exist_val                    = "";
							$employee_code                = "";
							$leave_type                   = "";
							$leave_date                   = "";
							$leave_count                  = "";
							$leave_status                 = "";
							$status_info                  = array();
							$err_status_info              = array();
							$status_info["Excel Row"]     = $row;
							$sts                          = TRUE;
							$email_sts                    = TRUE;
							$picklist_sts                 = TRUE;
							foreach($excel_format_result as $excel_info){
								$field_isdefault        = (int)$excel_info->field_isdefault;
								$mandatory_field        = (int)$excel_info->mandatory_field;
								$field_type             = (int)$excel_info->field_type;
								$pick_table             = $excel_info->pick_table;
								$pick_list_type         = (int)$excel_info->pick_list_type;
								$pick_list_import       = (int)$excel_info->pick_list_import;
								$pick_list              = $excel_info->pick_list;
								$excel_line_column_name = $excel_info->excel_line_column_name;
								$excel_line_value       = $excel_info->excel_line_value;
								$get_cell_value         = ucwords(trim($sheet->getCell("$excel_line_value$row")->getValue()));
	                            if($get_cell_value){
									//FOR LEAVE NAME(LABEL)
									if($excel_line_column_name === 'leave_type'){
										$get_cell_value    = str_replace(" ","_",strtolower($get_cell_value));
									}
									//FOR MOBILE NUMBER
									 if($field_type === 11){
										$length = strlen($get_cell_value);
										$length_query = 'select field_length from cw_form_setting where cw_form_setting.prime_module_id = "'.$module_id.'" and cw_form_setting.field_type = 11';
										$length_data  = $this->db->query("CALL sp_a_run ('SELECT','$length_query')");
										$length_result = $length_data->result();
										$length_data->next_result();
										$field_length = $length_result[0]->field_length;
										if($field_length != $length){
											$sts = FALSE;
										}
									}else 
									if($field_type === 12){
										//FOR EMAIL
										$email = $get_cell_value;
										if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
											$email_sts = FALSE;
										}
									}else
									if($field_type === 4){
										// FOR DATE
										$get_cell_value   = trim(Date::excelToDateTimeObject((int)$sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));
										$format           = "Y-m-d";

										$date             = DateTime::createFromFormat($format , $get_cell_value);

										$date_format_sts  = $date && $date->format($format) === $get_cell_value;
										if(!$date_format_sts){
											$err_column_array['error']["$excel_line_value$row"]   = "Invalid Date Format..Please Map Date Format like (DD/MM/YYYY)..!";
										}else
										if(($starting_date > $get_cell_value) || ($ending_date < $get_cell_value)){
											$err_column_array['error']["$excel_line_value$row"]   = "Invalid Date Format..Please Map Date Format like (DD/MM/YYYY)..!";
										}
									}else
									if($field_type === 13){
										$get_cell_value = trim(date('Y-m-d H:i:s',Date::PHPToExcel($sheet->getCell("$excel_line_value$row")->getValue())));
									}else
									// FOR PICKLIST CHECK
									if(($field_type === 5) || ($field_type === 7)){
										if($pick_list_type === 1){
											$pick_list_val   = explode(",",$pick_list);
											$pick_list_val_1 = $pick_list_val[0];
											$pick_list_val_2 = $pick_list_val[1];
											$pick_query = 'select '.$pick_list.',trans_status from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'" and '.$pick_table.'.trans_status = 1';
											if($pick_list_import === 1){
												$pick_query = 'select '.$pick_list.',trans_status from '.$pick_table.' where '.$pick_list_val_1.' = "'.$get_cell_value.'" and '.$pick_table.'.trans_status = 1';	
											}else{
												$pick_query = 'select '.$pick_list.',trans_status from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'" and '.$pick_table.'.trans_status = 1';
											}	
											$pick_data  = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
											$pick_result = $pick_data->result();
											$pick_count  = $pick_data->num_rows();
											$pick_data->next_result();
											if((int)$pick_count === 0){
												// $err_status_info["Excel Row"] = $row;
												$err_column_array['error']["$excel_line_value$row"]   = "Invalid $get_cell_value";
												$message                   = "Invalid $get_cell_value";
												$status                    = FALSE;
												$picklist_sts              = FALSE;
											}else
											if((int)$pick_count === 1){
												if($pick_table !== $this->prime_table){
													$pick_id     = $pick_result[0]->$pick_list_val_1;
													$pick_status = (int)$pick_result[0]->trans_status;
													if($pick_status === 0){
														$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
														$message                 = "Invalid $get_cell_value";
														$status                  = FALSE;
														$picklist_sts            = FALSE;
													}
													else
													if($pick_status === 1){
														$get_cell_value = $pick_id;
													}
												}
											}
										}else
										if($pick_list_type === 2){
											$pick_list_val_1 = $pick_table."_id";
											$pick_list_val_2 = $pick_table."_value";
											$pick_list_val_3 = $pick_table."_status";
											$pick_query = 'select * from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
											$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
											$pick_result = $pick_data->result();
											$pick_count  = $pick_data->num_rows();
											$pick_data->next_result();
											if((int)$pick_count === 0 && $mandatory_field === 0){
												$ins_query  = 'insert into '.$pick_table.'('.$pick_list_val_2.') VALUES ("'.$get_cell_value.'")';
												$ins_info   = $this->db->query("CALL sp_a_run ('INSERT','$ins_query')");
												$ins_result = $ins_info->result();
												$ins_info->next_result();
												$get_cell_value  = $ins_result[0]->ins_id;
											}else
											if((int)$pick_count === 0 && $mandatory_field === 1){
												// $err_status_info["$excel_line_value$row"] = "Invalid $get_cell_value";
												$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
												$message                 = "Invalid $get_cell_value";
												$status                  = FALSE;
												$picklist_sts            = FALSE;
											}else
											if((int)$pick_count === 1){
												$pick_id     = $pick_result[0]->$pick_list_val_1;
												$pick_status = (int)$pick_result[0]->$pick_list_val_3;
												if($pick_status === 0 && $mandatory_field === 1){
													$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
													$message                 = "Invalid $get_cell_value";
													$status                  = FALSE;
													$picklist_sts            = FALSE;
												}else
												if($pick_status === 0 && $mandatory_field === 0){
													$upd_query  = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = '.$pick_id;
													$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
													$get_cell_value = $pick_id;
												}else
												if($pick_status === 1){
													$get_cell_value = $pick_id;
												}
											}
										}
									}
									if($field_isdefault === 1){
										if($excel_line_column_name === 'employee_code'){
											$employee_code     = $get_cell_value;
											$component_value   = $employees_arr[$employee_code]['role'];
											$emp_doj           = $employees_arr[$employee_code]['date_of_joining'];
											$category          = $employees_arr[$employee_code]['role'];
											if(!in_array($employee_code,$active_emp_arr)){
												$error         = 1;
												$err_column_array['error']["$excel_line_value$row"] = "Invalid or In Active Employee( $employee_code)  Please Check in Employee Master.!";
												$picklist_sts  = FALSE;
											}	
											
											if(!$employees_arr[$employee_code] || !$category){
												$error         = 1;
												$err_column_array['error']["$excel_line_value$row"] = "Invalid $employee_code Employee code or Category Mapped. Please Check it.!";
												$picklist_sts  = FALSE;
											}else
											if(!$emp_doj){
												$error         = 1;
												$err_column_array['error']["$excel_line_value$row"] = "Date of Joining Empty Mapped.! for this $employee_code.. Please Check it.!";
												$picklist_sts  = FALSE;
											}
										}
										if($excel_line_column_name === 'leave_date'){
											$leave_date      = $get_cell_value;

											if($min_leave_date > $leave_date){
												$min_leave_date = $leave_date;
											}

											if($max_leave_date < $leave_date){
												$max_leave_date = $leave_date;
												$min_leave_date =  $leave_date;
											}
											if($last_pay_month){
												if($month_start_date > $leave_date){
													$error         = 1;
													$err_column_array['error']["$excel_line_value$row"] = "Payroll Already Processed Please Check Leave Date...!";
													$picklist_sts  = FALSE;
												}
											}
										}
										if($excel_line_column_name === 'leave_type'){
											$leave_type    = $get_cell_value;
										}
										if($excel_line_column_name === 'date_type'){
											$date_type   = (int)$get_cell_value;
										}
										if($excel_line_column_name === 'leave_count'){
											// $leave_count   = $get_cell_value;
											$leave_count   = floatval(number_format((float)$get_cell_value, 2, '.', ''));
										}
										if($excel_line_column_name === 'leave_status'){
											// $leave_count   = $get_cell_value;
											$leave_stauts  = $get_cell_value;
										}	

										if($excel_line_column_name === 'leave_status'){
											if($exist_check_arr[$employee_code][$leave_date][$leave_type]){
												$error         = 1;
												$err_column_array['error']["$excel_line_value$row"] = "Same Employee Code,Leave date,leave type Already Exist in Excel Please Check..!";
												$picklist_sts  = FALSE;
											}else
											if($exist_check_arr[$employee_code][$leave_date][$date_type]){
												$error         = 1;
												$err_column_array['error']["$excel_line_value$row"] = "Same Employee Code,Leave date,date type Already Exist in Excel Please Check..!";
												$picklist_sts  = FALSE;
											}
											$exist_check_arr[$employee_code][$leave_date][$leave_type]    = $employee_code;
											$exist_date_type_arr[$employee_code][$leave_date][$date_type] = $employee_code;			
											
											if($time_entry_data_arr[$employee_code][$leave_date]){				
												$first_hlf_sts   = $time_entry_data_arr[$employee_code][$leave_date]['first_half_status'];
												$second_hlf_sts  = $time_entry_data_arr[$employee_code][$leave_date]['second_half_status'];
												$whold_day_sts   = $time_entry_data_arr[$employee_code][$leave_date]['whole_day_status'];
												if((int)$date_type === 1 && (in_array($whold_day_sts,$fh_check_arr) || in_array($whole_day_status,$sh_check_arr))){
													$error         = 1;
													$err_column_array['error']["$excel_line_value$row"] = "One or More Date(s) Already Exists in Attendance Entry($whold_day_sts)";
													$picklist_sts  = FALSE;
												}else
												if((int)$date_type === 2 && in_array($whold_day_sts,$fh_check_arr)){
													$error         = 1;
													$err_column_array['error']["$excel_line_value$row"] = "One or More Date(s) Already Exists in Attendance Entry($first_hlf_sts)";
													$picklist_sts  = FALSE;
												}else
												if((int)$date_type === 3 && in_array($whold_day_sts,$sh_check_arr)){
													$error         = 1;
													$err_column_array['error']["$excel_line_value$row"] = "One or More Date(s) Already Exists in Attendance Entry($second_hlf_sts)";
													$picklist_sts  = FALSE;
												}												
											}
											if($employee_code && $leave_date && $date_type){
												$leave_exist_qry  = 'SELECT count(*) as from_exist_count  from cw_leave_entry WHERE employee_code = "'. $employee_code .'" and leave_date = "'.$leave_date.'" and financial_setting_id = '.$prime_financial_id.' and leave_status not in (3,4) and leave_type = "'.$leave_type.'" and trans_status = 1';
												$leave_exist_info  = $this->db->query("CALL sp_a_run ('SELECT','$leave_exist_qry')");
												$leave_exist_rslt  = $leave_exist_info->result();
												$leave_exist_info->next_result();
												$from_exist_rslt  = (int)$leave_exist_rslt[0]->from_exist_count;

												$same_type_exist  = 'SELECT leave_count,leave_type,date_type from cw_leave_entry WHERE employee_code = "'. $employee_code .'" and leave_date = "'.$leave_date.'" and financial_setting_id = '.$prime_financial_id.' and leave_status not in (3,4) and date_type = '.$date_type.' and trans_status = 1';
												$same_type_info   = $this->db->query("CALL sp_a_run ('SELECT','$same_type_exist')");
												$same_type_rslt   = $same_type_info->result();
												$same_type_info->next_result();
												$same_type_count   = count($same_type_rslt ?? []);
												$leave_exist_count = floatval(number_format((float)$same_type_rslt[0]->leave_count, 2, '.', ''));
												$sum_leave_count   = $leave_exist_count + $leave_count; 
												if($from_exist_rslt  > 0){
													$error         = 1;
													$err_column_array['error']["$excel_line_value$row"] = "Same Leave type Already Exist for this given Date...!";
													$picklist_sts  = FALSE;
												}
												if((int)$same_type_count > 0){
													$error         = 1;
													$err_column_array['error']["$excel_line_value$row"] = "Same Leave type Already Exist for this date type ...!";
													$picklist_sts  = FALSE;
												}
											}		
										}																

										if(($excel_line_column_name !== 'component_value') || ($excel_line_column_name !== 'financial_setting_id')){
											$get_cell_value    = str_replace("'",'^', $get_cell_value);
											$prime_column_val .= $excel_line_column_name . ",";
											$prime_cell_val   .= '"' . $get_cell_value . '",';
										}
										
										if(empty($exist_column_name)){
											if($mandatory_field === 1){
												$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
											}
										}else{
											if(in_array($excel_line_column_name,$exist_column_name)){
												if($excel_line_column_name !== "leave_date" && $excel_line_column_name !== "leave_type" && $excel_line_column_name !== "leave_status"){
													$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
												}
											}
										}
									}
								}else{
									$err_column_array['error']["$excel_line_value$row"] = "Column($excel_line_column_name) is Empty,Please Check Excel..!";
									$message                 = "Column is Empty Please Check Excel";
									$status                  = FALSE;
									$picklist_sts            = FALSE;
								}
							}	


							if($employee_code && $leave_date && $date_type){
								# Leave validation.
								if($validate_arr[$employee_code][$leave_date][1]){
									if((int)$date_type === 2 || (int)$date_type === 3){
										$err_column_array['error']["$excel_line_value$row"] = "Invalid - Full Day Request Already Submitted[$leave_date].";
										$error  = 1;
									}else if((int)$date_type === 1){
										$err_column_array['error']["$excel_line_value$row"] ="Invalid - Duplicate Entry, Data Already exist[$leave_date].";
										$error  = 1;
									}
								}else
								if($validate_arr[$employee_code][$leave_date][2] || $validate_arr[$employee_code][$leave_date][3]){
									if((int)$date_type === 1){
										$err_column_array['error']["$excel_line_value$row"] = "Invalid - 1ST HALF/2ND HALF Request Already Submitted[$leave_date].";
										$error  = 1;
									}else if($validate_arr[$employee_code][$leave_date][2] && (int)$date_type === 2 || $validate_arr[$employee_code][$leave_date][3] && (int)$date_type === 3){
										$err_column_array['error']["$excel_line_value$row"] ="Invalid - Duplicate Entry, Data Already exist[$leave_date].";
										$error  = 1;
									}
								}
							}					
							if($prime_column_val){
								$prime_id    = "prime_".$module_id."_id";
								$exist_val   = rtrim($exist_val," and ");
								if($exist_val === ""){
									$exist_val = 0; 
								}else{
									$exist_query  = "select count(*) exist_count,$this->prime_table.trans_status,$this->prime_table.$prime_id from $this->prime_table where $exist_val and cw_leave_entry.leave_date = \"$leave_date\" and (cw_leave_entry.date_type = 1 or cw_leave_entry.date_type = $date_type) and leave_type = \"$leave_type\" and $this->prime_table.leave_status in (1,2) and trans_status = 1";
									$exist_info   = $this->db->query("CALL sp_a_run ('RUN','$exist_query')");
									$exist_result = $exist_info->result();
									$exist_info->next_result();
									$exist_count  = $exist_result[0]->exist_count;
								}
								$created_on  = date("Y-m-d H:i:s");
								//DATE TYPE AND LEAVE COUNT BASED VALIDATION
								//FOR FULL DAY							
								if($date_type === 1 && $leave_count !== floatval(1) && in_array($leave_type,$leave_name_arr)){
									$error = 1;
									$err_column_array['error']["$row"] = "Your Date Type and Leave Count was Invalid, Please Check.!";
								}else//FOR 1ST HALF AND 2ND HALF
								if($date_type !== 1 && $leave_count !== floatval(0.5) && in_array($leave_type,$leave_name_arr)){
									$error = 1;
									$err_column_array['error']["$row"] = "Your Date Type and Leave Count was Invalid, Please Check.!";
								}else
								if($emp_doj > $leave_date){
									$error         = 1;
									$err_column_array['error']["$row"]    = "Leave Date Should not be Greater than Date of Joining Please Check it.!";
									$message                    = "Invalid Leave Date.!";
									$picklist_sts               = FALSE;
								}
								else
								if((int)$exist_count === 0 && $picklist_sts){
									$prime_column_val .= "component_value,financial_setting_id,trans_created_by,trans_created_date";
									$prime_cell_val   .= '"'.$component_value.'","'.$prime_financial_id.'","'.$this->logged_id.'","'.$created_on.'"';
									$prime_column_val  = rtrim($prime_column_val,",");
									$prime_cell_val    = rtrim($prime_cell_val,",");
									$prime_query_value .= "($prime_cell_val),";
									// PREPARE THE DATAS FOR COFF MOFF UPDATE -ARN 31-03-2026
									if((int)$leave_stauts === 2){
										$approved_arr[] = [
											'employee_code' => $employee_code,
											'leave_date'    => $leave_date,
											'leave_count'   => $leave_count,
											'leave_type'    => $leave_type
										];
									}

									//IF CONDITIONS FOR CHECK TO TIME ENTRY AND SHIFT MASTER AND LEAVE ENTRY
									if($employee_code && $leave_date && $leave_type && $leave_count && $date_type){
										$leave_opening = (int)$leave_creation_arr[$leave_type]['leave_opening'];
										//GET LEAVE NAME USING LEAVE ID
										$leave_type    = str_replace(" ","_",$leave_creation_arr[$leave_type]['leave_name']);
										if(!$leave_type){
											$error = 1;
											$err_column_array['error']["$row"] = "Invalid Leave Name Mapped Please check Leave Creation Master.!";
										}

										if($employee_code && $category){
											//function for get a MONTH DAY RELATED INFORMATION
											$month_day_info    =  $this->month_day_qry_fun($category);
										}
										//LEAVE COUNT CHECK ONLY FOR LEAVE OPENING YES LEAVE TYPE
										if($leave_type && $leave_opening === 1){
											$opening_arr[$employee_code][$leave_type] += $leave_count;
											//for we check used leve count from above array (because in loop from same employee count should be create in array for we check leave balance count)
											$check_leave_count    = $opening_arr[$employee_code][$leave_type];
											//Get Balance count from opening array
											$balance_leave_count  = $opening_balance_used_arr[$employee_code]["balance_".$leave_type];
											//balance count and leve import count check 
											if($balance_leave_count < $check_leave_count){
												$error = 1;
												$upper_leave_type        = strtoupper($leave_type);
												$err_column_array['error']["$row"] = "$employee_code in Leave Balance Not Available for this $upper_leave_type Leave...!!";
											}
										}
										if($employee_code && $leave_date && $date_type){
											//shift name and details get from shift master
											$shift_time_qry     = 'select cw_shift_master.prime_shift_master_id,cw_shift_import.employee_code as employee_code,cw_shift_master.shift_name,cw_shift_import.shift_date as shift_date,cw_shift_import.from_date as from_date,cw_shift_master.from_time as from_time,cw_shift_import.to_date as to_date,cw_shift_master.to_time as to_time,cw_shift_master.first_half as first_half,cw_shift_master.second_half as second_half,cw_shift_master.shift_status as shift_status 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 = "'.$leave_date.'" and cw_shift_import.trans_status = 1';
											$shift_time_info   = $this->db->query("CALL sp_a_run ('SELECT','$shift_time_qry')");
											$shift_time_rslt   = $shift_time_info->result_array();
											$shift_time_info->next_result();

											$shift_master_id    = $shift_time_rslt[0]['prime_shift_master_id'];
											$shift_name         = $shift_time_rslt[0]['shift_name'];
											$shift_status       = (int)$shift_time_rslt[0]['shift_status'];

											if(!$shift_master_id){
												$error = 1;
												$err_column_array['error']["$row"] = "Shift not mapped for this Leave Date.! Please check Shift Master.?";
											}else{
												$status_info['Status'] = "Inserted to DB";	
											}
										}
									}	
								}else
								if($picklist_sts){
									$error = 1;
									$err_column_array['error']["$row"] = "Already Exist in DB";
								}

								$status_array[]     = $status_info;
							}
						}
						$err_column_count = count($err_column_array['error'] ?? []);
						if($err_column_count > 0){
							$table_info   = $this->get_excel_error_ui($err_column_array);
							return json_encode(array('success'=>false,'message'=>" file not imported",'table_info'=>$table_info));
						}else{
							if((int)$error === 0 && $picklist_sts){
								$prime_query_value     = rtrim($prime_query_value,",");
								if($prime_query_value){
									$prime_query          = "insert into $this->prime_table ($prime_column_val) VALUES $prime_query_value";	
									$insert_info          = $this->db->query($prime_query);
									//Modified by Ragu (Removed time entry insert function and just call procedure)
									//procedure call between minimum date of request date and maximum date of request date in excel 
									/*$info              = $this->db->query("CALL itsp_prcatt ('$min_leave_date','$max_leave_date',NULL)");
									$result            = $info->result();
									$info->next_result();	*/	
									#Update coff moff entries 
									if(!empty($approved_arr)){
										$this->bulk_coff_moff_update($approved_arr);
									}					
									if(count($opening_arr ?? [])){
										$this->update_used_leave($opening_arr,$opening_balance_used_arr,$prime_financial_id);
									}										
								}	
								$table_info = $this->get_excel_import_ui($status_array);
								return json_encode(array('success'=>true,'message'=>"Successfully file imported",'table_info'=>$table_info));
							}
						}
					}	
				}
			}
		}
	}
	
	//FOR MANUAL PUNCH IMPORT
	public function do_excel_manual_punch_import($import_id,$category,$process_month){
		$leave_financial_info  = $this->get_leave_financial_details();
		$prime_financial_id    = $leave_financial_info[0]->prime_leave_financial_year_id;
		$starting_date         = date('Y-m-d',strtotime($leave_financial_info[0]->starting_date));	
		$ending_date           = date('Y-m-d',strtotime($leave_financial_info[0]->ending_date));	
		//CATEGORY BASED SALARY START DATE AND END DATE DETAILS
		$company_info          = $this->company_info();
		$mp_treat_time_log     = $company_info[0]->mp_treat_as;
		$salary_info_arr       = $this->salary_start_end_info($category,$process_month);

		$salary_start_date     = date('Y-m-d',strtotime($salary_info_arr['salary_start_date']));
		$salary_end_date       = date('Y-m-d',strtotime($salary_info_arr['salary_end_date']));	
		$emp_name_arr          = "";
		$time_entry_arr        = "";
		$leave_entry_arr       = "";
		$on_duty_entry_arr     = "";
		$shift_request_arr     = "";
		$shift_details_arr     = "";
		$shift_import_arr      = "";
		$man_punch_exist_arr   = "";
		$prime_query_value     = "";
		$time_entry_upd_value  = "";
		$time_entry_ins_value  = "";
		 
		$filename              = dirname(__FILE__)."/php_excel/PHPExcel/IOFactory.php";
		include($filename);
		if($import_id < 0){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}		
		$excel_path_qry    = 'select * from cw_import where import_id = "'.$import_id.'"';
		$excel_path_info   = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
		$excel_path_result = $excel_path_info->result();
		$excel_path_info->next_result();
		
		if(!$excel_path_result){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}else{
			$excel_file_path    = $excel_path_result[0]->excel_file_path;
			$module_id          = $excel_path_result[0]->module_id;
			$excel_format       = $excel_path_result[0]->excel_format;
			$excel_sheet_name   = (int)$excel_path_result[0]->excel_sheet_name;
			$excel_row_start    = (int)$excel_path_result[0]->excel_start_row;
			$excel_row_end      = (int)$excel_path_result[0]->excel_end_row;
			
			$format_qry 	= 'select * from cw_util_excel_format where prime_excel_format_id = "'.$excel_format.'" and cw_util_excel_format.trans_status = 1';
			$format_info    = $this->db->query("CALL sp_a_run ('SELECT','$format_qry')");
			$format_rslt    = $format_info->result();
			$format_info->next_result();
			
			if(!$format_rslt){
				return json_encode(array('success' => false, 'message' => "Please add excel format before import"));
			}else{
				$exist_column_name   = explode(",",$format_rslt[0]->exist_column_name);
				$excel_format_qry 	 = 'select field_type,pick_table,pick_list_type,pick_list_import,pick_list,mandatory_field,field_isdefault,excel_line_column_name,excel_line_value from cw_util_excel_format_line inner join cw_form_setting on label_name = excel_line_column_name where excel_line_module_id = "'.$module_id.'" and prime_excel_format_id = "'.$excel_format.'" and cw_form_setting.prime_module_id = "'.$module_id.'" and cw_util_excel_format_line.trans_status = 1 ORDER BY cw_util_excel_format_line.excel_line_value ASC';			
				$excel_format        = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
				$excel_format_result = $excel_format->result();
				$excel_format->next_result();

				if(!$excel_format_result){
					return json_encode(array('success' => false, 'message' => "Please map excel cell column before import"));
				}else{
					try{
						$excel_obj = \PhpOffice\PhpSpreadsheet\IOFactory::load($excel_file_path);
					}catch(Exception $e){
						die('Error loading file "' . pathinfo($excel_file_path, PATHINFO_BASENAME). '": ' . $e->getMessage());
						return json_encode(array('success' => false, 'message' => "Invalid file or path"));
					}
					$sheet           = $excel_obj->getSheet($excel_sheet_name);
					if($excel_row_end){
						$total_rows = $excel_row_end;
					}else{
						$total_rows = $sheet->getHighestRow();
					}
					$highest_column          = $sheet->getHighestColumn();
					$worksheetTitle          = $sheet->getTitle();
					$status_array	         = array();
					$leave_creation_arr      = array();
					$opening_used_arr        = array();
					$opening_arr	         = array();
					$post_data_arr           = array(); 
					$prime_query_value       = "";
					$prime_upd_query_value   = "";

					//function for get a last payroll processed date
					//GET EMPLOYEE NAME FROM EMPLOYEE MASTER
					// $emp_name_qry      = 'select employee_code,emp_name,date_of_joining from cw_employees where trans_status = 1 and (cw_employees.termination_status = 0 or cw_employees.resignation_date >= "'.$salary_start_date.'")';
					// $emp_name_info     = $this->db->query("CALL sp_a_run ('RUN','$emp_name_qry')");
					// $emp_name_result   = $emp_name_info->result_array();
					// $emp_name_info->next_result();

					// $emp_name_arr      = array();
					// foreach($emp_name_result as $emp_key => $emp_val){
					// 	$employee_code   = $emp_val['employee_code'];
					// 	$emp_name_arr[$employee_code]  = $emp_val;
					// }

					$employee_codes_arr = $this->get_excel_employee_codes($sheet,$excel_row_start,$total_rows,$excel_format_result,$module_id);
					$employee_count = count($employee_codes_arr['employee_codes_arr'] ?? []); 

					if((int)$employee_count <= 0){
						echo json_encode(array('success'=>false,'message'=>"Please check Employee Code Column in your Excel Sheet...",'table_info'=>""));
						exit(0);
					}
					$employee_codes     = trim(implode('","',$employee_codes_arr['employee_codes_arr'] ?? []));

					//GET EMPLOYEE DETAILS FROM EMPLOYEE MASTER
					$emp_details_qry      = 'select employee_code,role as category,emp_name,date_of_joining,department,approve_type,first_level_approval,second_level_approval,termination_status,resignation_date from cw_employees where cw_employees.employee_code in ("'.$employee_codes.'") and cw_employees.trans_status = 1';
					$emp_details_info     = $this->db->query("CALL sp_a_run ('RUN','$emp_details_qry')");
					$emp_details_result   = $emp_details_info->result_array();
					$emp_details_info->next_result();

					$emp_name_arr      = array();
					foreach($emp_details_result as $emp_key => $emp_val){
						$employee_code   = $emp_val['employee_code'];
						$emp_name_arr[$employee_code]  = $emp_val;
					}
					//SHIFT REQUEST STATUS ARRAY
					$shift_request_qry    = 'SELECT cw_request.employee_code,cw_request.shift_date FROM cw_request WHERE cw_request.request_type = "6" and cw_request.leave_status in (1) and cw_request.employee_code in ("'.$employee_codes.'") and cw_request.shift_date >= "'.$salary_start_date.'" and financial_setting_id = "'.$financial_year_id.'" and trans_status = 1';
					// and cw_request.leave_status in (1,2)
					$shift_request_info   = $this->db->query("CALL sp_a_run ('SELECT','$shift_request_qry')");
					$shift_request_rslt   = $shift_request_info->result_array();
					$shift_request_info->next_result();

					$shift_request_arr    = array();
					foreach($shift_request_rslt as $shift_key => $shift_val){
						$shift_emp_code    = $shift_val['employee_code'];
						$shift_date        = $shift_val['shift_date'];
						$shift_request_arr[$shift_emp_code][$shift_date]   = $shift_date;
					}
					// $shift_request_arr    = array_reduce($shift_request_rslt, function ($result, $arr) {
					// 	$result[$arr['employee_code']][$arr['shift_date']] = $arr['shift_date'];
					// 	return $result;
					// }, array());

					//QUERY FOR CHECK EXIST DATA FROM LEAVE ENTRY TABLE 
					$leave_entry_qry    = 'select employee_code,leave_date from cw_leave_entry where trans_status = 1 and leave_status NOT IN (3,4) and financial_setting_id = "'.$prime_financial_id.'" and cw_leave_entry.leave_date >= "'.$salary_start_date.'" and cw_leave_entry.employee_code in ("'.$employee_codes.'")';
					$leave_entry_info   = $this->db->query("CALL sp_a_run ('RUN','$leave_entry_qry')");
					$leave_entry_result = $leave_entry_info->result_array();
					$leave_entry_info->next_result();

					// $leave_entry_arr    = array_reduce($leave_entry_result, function ($result, $arr) {
					// 	$result[$arr['employee_code']][$arr['leave_date']] = $arr['leave_date'];
					// 	return $result;
					// }, array());

					$leave_entry_arr    = array();
					foreach($leave_entry_result as $leave_key => $leave_val){
						$leave_emp_code    = $leave_val['employee_code'];
						$leave_date        = $leave_val['leave_date'];
						$leave_entry_arr[$leave_emp_code][$leave_date]   = $leave_date;
					}

					//QUERY FOR CHECK EXIST DATA FROM ON DUTY ENTRY TABLE 
					$on_duty_entry_qry  = 'select employee_code,on_duty_date from cw_on_duty_entry where trans_status = 1 and on_duty_status NOT IN (3,4) and financial_setting_id = "'.$prime_financial_id.'" and cw_on_duty_entry.on_duty_date >= "'.$salary_start_date.'" and cw_on_duty_entry.employee_code in ("'.$employee_codes.'")';
					$on_duty_entry_info = $this->db->query("CALL sp_a_run ('SELECT','$on_duty_entry_qry')");
					$on_duty_entry_rslt = $on_duty_entry_info->result_array();
					$on_duty_entry_info->next_result();

					// $on_duty_entry_arr  = array_reduce($on_duty_entry_rslt, function ($result, $arr) {
					// 	$result[$arr['employee_code']][$arr['on_duty_date']] = $arr['on_duty_date'];
					// 	return $result;
					// }, array());

					$on_duty_entry_arr    = array();
					foreach($on_duty_entry_rslt as $od_key => $od_val){
						$od_emp_code       = $od_val['employee_code'];
						$od_date           = $od_val['leave_date'];
						$on_duty_entry_arr[$od_emp_code][$od_date]   = $od_date;
					}

					//QUERY FOR CHECK EXIST DATA FROM TIME ENTRY TABLE 
					$time_entry_qry     = 'select * from cw_time_entry where trans_status = 1 and cw_time_entry.att_date >= "'.$salary_start_date.'" and cw_time_entry.employee_code in ("'.$employee_codes.'")';
					$time_entry_info    = $this->db->query("CALL sp_a_run ('RUN','$time_entry_qry')");
					$time_entry_result  = $time_entry_info->result_array();
					$time_entry_info->next_result();

					$time_entry_arr     = array();
					foreach($time_entry_result as $time_key => $time_val){
						$att_emp_code       = $time_val['employee_code'];
						$att_date           = $time_val['att_date'];
						$time_entry_arr[$att_emp_code][$att_date]   = $time_val;
					}

					// $time_entry_arr     = array_reduce($time_entry_result, function ($result, $arr) {
					// 	$result[$arr['employee_code']][$arr['att_date']] = $arr;
					// 	return $result;
					// }, array());

					//QUERY FOR CHECK EXIST DATA FROM SHIFT IMPORT TABLE 
					// $shift_import_exist_qry    = 'select cw_shift_master.*,cw_shift_import.prime_shift_import_id,cw_shift_import.cw_shift_import.employee_code,cw_shift_import.shift_date,cw_shift_import.shift_name from cw_shift_master inner join cw_shift_import on cw_shift_import.shift_name = cw_shift_master.prime_shift_master_id where cw_shift_import.shift_date >= "'.$salary_start_date.'" and cw_shift_import.financial_setting_id ="'.$prime_financial_id.'" and  cw_shift_import.trans_status = 1,cw_shift_master.trans_status = 1';



					
					// $shift_import_exist_qry    = 'SELECT cw_shift_master.*, cw_shift_import.prime_shift_import_id, cw_shift_import.employee_code, cw_shift_import.shift_date, cw_shift_import.shift_name FROM cw_shift_master INNER JOIN cw_shift_import ON cw_shift_import.shift_name = cw_shift_master.prime_shift_master_id WHERE cw_shift_import.shift_date >= "'.$salary_start_date.'" AND cw_shift_import.financial_setting_id = "'.$prime_financial_id.'" AND cw_shift_import.trans_status = 1 AND cw_shift_master.trans_status = 1';
					$shift_import_exist_qry    = 'select cw_shift_master.*,cw_shift_import.employee_code,cw_shift_import.shift_date,cw_shift_import.shift_name as shift_id from cw_shift_master inner join   cw_shift_import on cw_shift_import.shift_name = cw_shift_master.prime_shift_master_id where employee_code in ("'.$employee_codes.'") and cw_shift_import.financial_setting_id ="'.$prime_financial_id.'" and cw_shift_import.trans_status = 1 and cw_shift_master.trans_status = 1';

					$shift_import_exist_info   = $this->db->query("CALL sp_a_run ('RUN','$shift_import_exist_qry')");
					$shift_import_exist_result = $shift_import_exist_info->result_array();
					$shift_import_exist_info->next_result();

					// $shift_master_import_arr   = array_reduce($shift_import_exist_result, function ($result, $arr) {
					// 	$result[$arr['employee_code']][$arr['shift_date']] = $arr;
					// 	return $result;
					// }, array());

					// $shift_details_arr   = array_reduce($shift_import_exist_rslt, function ($result, $arr) {
					// 	$result[$arr['employee_code']][$arr['shift_date']] = $arr;
					// 	return $result;
					// }, array());

					$shift_details_arr   = array();
					foreach($shift_import_exist_result as $imp_key => $imp_val){
						$imp_emp_code    = $imp_val['employee_code'];
						$imp_shift_date  = $imp_val['shift_date'];
						$shift_details_arr[$imp_emp_code][$imp_shift_date]  = $imp_val;
					}
					//QUERY FOR CHECK EXIST DATA FROM MANUAL PUNCH ENTRY TABLE 
					$man_punch_exist_qry  = 'select cw_manual_punch_entry.employee_code,cw_manual_punch_entry.shift_date from cw_manual_punch_entry where financial_setting_id ="'.$prime_financial_id.'" and cw_manual_punch_entry.leave_status in (1,2) and cw_manual_punch_entry.shift_date >= "'.$salary_start_date.'" and cw_manual_punch_entry.employee_code in ("'.$employee_codes.'") and trans_status = 1';
					$man_punch_exist_info = $this->db->query("CALL sp_a_run ('RUN','$man_punch_exist_qry')");
					$man_punch_exist_rslt = $man_punch_exist_info->result_array();
					$man_punch_exist_info->next_result();

					$man_punch_exist_arr   = array();
					foreach($man_punch_exist_rslt as $man_key => $man_val){
						$imp_emp_code    = $man_val['employee_code'];
						$imp_shift_date  = $man_val['shift_date'];
						$man_punch_exist_arr[$imp_emp_code][$imp_shift_date]  = $imp_shift_date;
					}
					
					// $man_punch_exist_arr  = array_reduce($man_punch_exist_rslt, function ($result, $arr){
					// 	$result[$arr['employee_code']][$arr['in_date']] = $arr['day_type'];
					// 	return $result;
					// }, array());
						
					//this query check only for forgot punch reason
					$man_punch_forgot_qry  = 'SELECT employee_code,COUNT(prime_manual_punch_entry_id) as count from cw_manual_punch_entry where cw_manual_punch_entry.employee_code in ("'.$employee_codes.'") and leave_status in (1,2) and mp_reason = 2 and cw_manual_punch_entry.trans_status = 1 and cw_manual_punch_entry.shift_date >= "'.$salary_start_date.'" group by cw_manual_punch_entry.employee_code';
					$man_punch_forgot_info = $this->db->query("CALL sp_a_run ('SELECT','$man_punch_forgot_qry')");
					$man_punch_forgot_rslt = $man_punch_forgot_info->result_array();
					$man_punch_forgot_info->next_result();
					
					// $man_punch_forgot_arr  = array_reduce($man_punch_forgot_rslt, function ($result, $arr){
					// 	$result[$arr['employee_code']] = $arr['count'];
					// 	return $result;
					// }, array());	
					
					$man_punch_forgot_arr   = array();
					foreach($man_punch_forgot_rslt as $man_for_key => $man_for_val){
						$imp_emp_code    = $man_for_val['employee_code'];
						$forgot_count    = $man_for_val['count'];
						$man_punch_forgot_arr[$imp_emp_code]  = $forgot_count;
					}
					
					$day_status_legend_qry  = 'select legends,day_description,day_type from cw_day_status_legends where cw_day_status_legends.trans_status = 1';
					$day_status_legend_info = $this->db->query("CALL sp_a_run ('SELECT','$day_status_legend_qry')");
					$day_status_legend_rslt = $day_status_legend_info->result_array();
					$day_status_legend_info->next_result();

					$day_status_legend_arr  = array_reduce($day_status_legend_rslt, function($result, $arr){
						$result[$arr['legends']] = $arr;
						return $result;
					}, array());
					for($row =$excel_row_start; $row <= $total_rows; $row++) {
						$prime_column_val = "";
						$prime_cell_val   = "";
						$exist_val        = "";
						$status_info = array();
						$status_info["Excel Row"] = $row;
						$sts = TRUE;
						$email_sts = TRUE;
						foreach($excel_format_result as $excel_info){
							
							$field_isdefault        = (int)$excel_info->field_isdefault;
							$mandatory_field        = (int)$excel_info->mandatory_field;
							$field_type             = (int)$excel_info->field_type;
							$pick_table             = $excel_info->pick_table;
							$pick_list_type         = (int)$excel_info->pick_list_type;
							$pick_list_import       = (int)$excel_info->pick_list_import;
							$pick_list              = $excel_info->pick_list;
							$excel_line_column_name = $excel_info->excel_line_column_name;
							$excel_line_value       = $excel_info->excel_line_value;
							$get_cell_value         = ucwords(trim($sheet->getCell("$excel_line_value$row")->getValue()));

                            if($get_cell_value){
								//FOR MOBILE NUMBER
								/*if($field_type === 11){
									$length = strlen($get_cell_value);
									$length_query = 'select field_length from cw_form_setting where cw_form_setting.prime_module_id = "'.$module_id.'" and cw_form_setting.field_type = 11';
									$length_data  = $this->db->query("CALL sp_a_run ('SELECT','$length_query')");
									$length_result = $length_data->result();
									$length_data->next_result();
									$field_length = $length_result[0]->field_length;
									if($field_length != $length){
										$sts = FALSE;
									}
								}else */
								if($field_type === 12){
									//FOR EMAIL
									$email = $get_cell_value;
									if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
										$email_sts = FALSE;
									}
								}else
								if($field_type === 4){
									// FOR DATE
									$salary_start_date     = date('Y-m-d',strtotime($salary_info_arr['salary_start_date']));
									$salary_end_date       = date('Y-m-d',strtotime($salary_info_arr['salary_end_date']));	
									$get_cell_value   = trim(Date::excelToDateTimeObject((int)$sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));
									$format           = "Y-m-d";
									$date             = DateTime::createFromFormat($format , $get_cell_value);

									$date_format_sts  = $date && $date->format($format) === $get_cell_value;
									if(!$date_format_sts){
										$err_column_array['error']["$excel_line_value$row"]   = "Invalid Date Format..Please Map Date Format like (DD/MM/YYYY)..!";
									}
									// else
									// if(($salary_start_date > $get_cell_value) || ($salary_end_date < $get_cell_value)){
									// 	$err_column_array['error']["$excel_line_value$row"]   = "Invalid Date Format..Please Map Date Format like (DD/MM/YYYY) or Your In Date and Out Date in Between Salary Date..!";
									// }
								}else
								if($field_type === 13){
									$get_cell_value = trim(date('Y-m-d H:i:s',Date::PHPToExcel($sheet->getCell("$excel_line_value$row")->getValue())));
								}else
								// FOR PICKLIST CHECK
								if(($field_type === 5) || ($field_type === 7)){
									if($pick_list_type === 1){
										$pick_list_val   = explode(",",$pick_list);
										$pick_list_val_1 = $pick_list_val[0];
										$pick_list_val_2 = $pick_list_val[1];
										$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
										if($pick_list_import === 1){
											$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_1.' = "'.$get_cell_value.'"';	
										}else{
											$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
										}	
										$pick_data  = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
										$pick_result = $pick_data->result();
										$pick_count  = $pick_data->num_rows();
										$pick_data->next_result();
										if((int)$pick_count === 0){
											$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
										}else
										if((int)$pick_count === 1){
											if($pick_table !== $this->prime_table){
												$pick_id     = $pick_result[0]->$pick_list_val_1;
												$pick_status = (int)$pick_result[0]->trans_status;
												if($pick_status === 0){
													$upd_query  = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = '.$pick_id;
													$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
												}
												$get_cell_value = $pick_id;
											}
										}
									}else
									if($pick_list_type === 2){
										$pick_list_val_1 = $pick_table."_id";
										$pick_list_val_2 = $pick_table."_value";
										$pick_list_val_3 = $pick_table."_status";
										$pick_query = 'select * from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
										$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
										$pick_result = $pick_data->result();
										$pick_count  = $pick_data->num_rows();
										$pick_data->next_result();
										if((int)$pick_count === 0){
											$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
										}else
										if((int)$pick_count === 1){
											$pick_id     = $pick_result[0]->$pick_list_val_1;
											$pick_status = (int)$pick_result[0]->$pick_list_val_3;
											if($pick_status === 0){
												$upd_query  = 'update '.$pick_table.' set '.$pick_list_val_3.' = 1 where '.$pick_list_val_1.' = '.$pick_id;
												$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
											}
											$get_cell_value = $pick_id;
										}
									}
								}
								if($field_isdefault === 1){
									if($excel_line_column_name === 'employee_code'){
										$emp_code_col_name  = $excel_line_value;
										$employee_code      = $get_cell_value;
										$employee_name      = $emp_name_arr[$employee_code]['emp_name'];
										$check_emp_code     = $emp_name_arr[$employee_code]['employee_code'];
										$category           = $emp_name_arr[$employee_code]['category'];
										$emp_doj            =  date("Y-m-d",strtotime($emp_name_arr[$employee_code]['date_of_joining']));
										$approve_type       = $emp_name_arr[$employee_code]['approve_type'];
										$department         = $emp_name_arr[$employee_code]['department'];
										$active_sts         = (int)$emp_name_arr[$employee_code]['termination_status'];
										$resign_date        = date("Y-m-d",strtotime($emp_name_arr[$employee_code]['resignation_date']));
										$first_level        = $emp_name_arr[$employee_code]['first_level_approval'];
										$second_level       = $emp_name_arr[$employee_code]['second_level_approval'];
										$post_data_arr[$excel_line_column_name] = $get_cell_value;
										//CATEGORY BASED SALARY START DATE AND END DATE DETAILS
										$salary_start_date  = $this->active_salary_date[$category]['salary_start_date'];
										$salary_end_date    = $this->active_salary_date[$category]['salary_end_date'];
										
										$applied_on         = date('Y-m-d');
										if(!$check_emp_code){
											$err_column_array['error']["$excel_line_value$row"] = "This Employee Code ($employee_code) or Employee Name not Present in the Employee Master? Please Check it..!";
										}
									}else
									if($excel_line_column_name === "shift_date"){
										$shift_date          = date('Y-m-d',strtotime($get_cell_value));
										$next_date           = date('Y-m-d',strtotime('+1 day',strtotime($shift_date)));
										$prev_date           = date('Y-m-d',strtotime('-1 day',strtotime($shift_date)));
										$shift_date_col_name = $excel_line_value;
										$dis_shift_date      = date('d-m-Y',strtotime($shift_date));
										$post_data_arr[$excel_line_column_name] = $shift_date;
										if($shift_date < $salary_start_date){
											$err_column_array['error']["$excel_line_value$row"] = "Shift Date Should be inbetween Current Month Attendance Date.. Past Date Not Allowed..!";
										}else
										if($shift_date > $applied_on){
											$err_column_array['error']["$excel_line_value$row"] = "Shift Date Should not be Greater than today..!";
										}
									}else
									if($excel_line_column_name === "shift_name"){
										$shift_name           = $get_cell_value;
										$post_data_arr[$excel_line_column_name] = $shift_name;
										// echo $shift_name; die;
									}else
									if($excel_line_column_name === "in_date"){
										$in_date           = date('Y-m-d',strtotime($get_cell_value));
										$in_date_col_name  = $excel_line_value;
										$dis_in_date       = date('d-m-Y',strtotime($in_date));
										$post_data_arr[$excel_line_column_name] = $in_date;
									}else
									if($excel_line_column_name === "out_date"){
										$out_date          = date('Y-m-d',strtotime($get_cell_value));
										$out_date_col_name = $excel_line_value;
										$dis_out_date      = date('d-m-Y',strtotime($out_date));
										$post_data_arr[$excel_line_column_name] = $out_date;
									}else
									if($excel_line_column_name === "in_time"){
										$in_time_col_name  = $excel_line_value;
										$get_datetime      = trim(date('H:i',Date::PHPToExcel($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
										$newhours          = date('H:i', strtotime($get_datetime. ' -5 hours'));
										$in_time           = date('H:i', strtotime($newhours. ' -30 minutes'));
										$post_data_arr[$excel_line_column_name] = $in_time;
									}else
									if($excel_line_column_name === "out_time"){
										$out_time_col_name = $excel_line_value;
										$get_datetime      = trim(date('H:i',Date::PHPToExcel($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
										$newhours          = date('H:i', strtotime($get_datetime. ' -5 hours'));
										$out_time          = date('H:i', strtotime($newhours. ' -30 minutes'));
										$post_data_arr[$excel_line_column_name] = $out_time;
										if($in_date && $out_date){
											if($in_date === $out_date){
												if($in_time >= $out_time){
													(int)$exist_count += 1;
													if($exist_count === 1){
														$err_column_array['error']["$excel_line_value$row"] = "Out Time should be Greater than In Time Check it..!";
														$exist_count++;
													}
												}	
											}else
											if($in_date !== $out_date){
												if($in_time <= $out_time){
													(int)$exist_count += 1;
													if($exist_count === 1){
														$err_column_array['error']["$excel_line_value$row"] = "In Time should be Greater than Out Time Please Check..!";
														$exist_count++;
													}
												}
											}
										}
										$total_time     = $this->total_time_cal($in_date,$out_date,$in_time,$out_time,2,2);
										if(!$total_time){
											(int)$exist_count += 1;
											if($exist_count === 1){
												$err_column_array['error']["$shift_date_col_name$row"] = "please Check In Time or Out Time for $dis_shift_date..";
												$exist_count++;
											}
										}
									}else
									if($excel_line_column_name === "day_type"){
										$day_type_col_name  = $excel_line_value;
										$day_type           = (int)$get_cell_value; 
										$date_type           = (int)$get_cell_value;
										$post_data_arr[$excel_line_column_name] = $day_type;
									}
									else
									if($excel_line_column_name === "mp_reason"){
										$mp_reason          = (int)$get_cell_value; 
										$post_data_arr[$excel_line_column_name] = $mp_reason;
									}
									
									if(empty($exist_column_name)){
										 if($mandatory_field === 1){
											$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
										}
									}else{
										if(in_array($excel_line_column_name,$exist_column_name)){
											$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
										}
									}
								}
							}else{
								(int)$exist_count += 1;
								if($exist_count === 1){
									$err_column_array['error']["$entry_date_col_name$row"] = "Please Map All Excel Column Data.!";
									$exist_count++;
								}
							}
						}
						if($shift_date && $in_date && $out_date && $in_time && $out_time && $total_time && $day_type){
							//CHECK SHIFT REQUEST DATE IN REQUEST MODULE
							$shift_request_date    = $shift_request_arr[$employee_code][$shift_date];
							
							//CONDITION FOR CHECK A LEAVE ENTRY EXIST OR NOT
							$check_leave_entry     = $leave_entry_arr[$employee_code][$shift_date];

							//CONDITION FOR CHECK A ON DUTY ENTRY EXIST OR NOT
							$check_on_duty_entry   = $on_duty_entry_arr[$employee_code][$shift_date];

							//CHECK ALREADY EXIST MANUAL PUNCH ENTRY
							$exist_man_punch       = $man_punch_exist_arr[$employee_code][$shift_date];

							//CHECK MANUAL PUNCH FORGOT ID REASON COUNT
							$punch_forgot_count    = $man_punch_forgot_arr[$employee_code];

							//CONDITION FOR CHECK A TIME ENTRY EXIST IF EXIST NOT UPDATE TO SHIFT IMPORT
							// $check_time_entry   = $time_entry_arr[$employee_code][$punch_date];
							if($emp_doj){
								if($emp_doj > $shift_date){
									(int)$exist_count += 1;
									if($exist_count === 1){
										$err_column_array['error']["$entry_date_col_name$row"] = "Shift Date Should be Greater than Date of Joining Please Check it..!!";
										$exist_count++;
									}
								}else{
									if($active_sts === 1){
										if($resign_date){
											if($resign_date < $salary_start_date){
												(int)$exist_count += 1;
												if($exist_count === 1){
													$err_column_array['error']["$emp_code_col_name$row"] = "Don't Import a Resigned Employee for this Attendance Month? Please Check it..!!";
													$exist_count++;
												}
											}else
											if($resign_date < $shift_date){
												(int)$exist_count += 1;
												if($exist_count === 1){
													$err_column_array['error']["$shift_date_col_name$row"] = "Don't Import a Resigned Employee for this $dis_shift_date? Please Check it..!!";
													$exist_count++;
												}
											}
										}else{
											(int)$exist_count += 1;
											if($exist_count === 1){
												$err_column_array['error']["$emp_code_col_name$row"] = "Please Map Resigned Date for this Employee? Please Check it..!!";
												$exist_count++;
											}
										}
									}
									if($shift_date){
										if($excel_exist_arr[$employee_code][$shift_date]){
											(int)$exist_count += 1;
											if($exist_count === 1){
												$err_column_array['error']["$shift_date_col_name$row"] = "For $dis_shift_date Already Exist In Your Excel Sheet? Please Check..!!";
												$exist_count++;
											}
										}else
										if($shift_request_date){
											(int)$exist_count += 1;
											if($exist_count === 1){
												$err_column_array['error']["$shift_date_col_name$row"] = "In $dis_shift_date Shift Request was Pending Please Check it..!!";
												$exist_count++;
											}
										}else
										if($check_leave_entry){
											(int)$exist_count += 1;
											if($exist_count === 1){
												$err_column_array['error']["$shift_date_col_name$row"] = "In $dis_shift_date Already Leave Request Exist Please Check it..!!";
												$exist_count++;
											}
										}else
										if($check_on_duty_entry){
											(int)$exist_count += 1;
											if($exist_count === 1){
												$err_column_array['error']["$shift_date_col_name$row"] = "In $dis_shift_date Already OD Request Exist Please Check it..!!";
												$exist_count++;
											}
										}else
										if($exist_man_punch){
											(int)$exist_count += 1;
											if($exist_count === 1){
												$err_column_array['error']["$shift_date_col_name$row"] = "In $dis_shift_date Already Manual Punch Request Exist Please Check it..!!";
												$exist_count++;
											}
										}else{
											if($mp_reason === 2){
												if($punch_forgot_count >=3){
													(int)$exist_count += 1;
													if($exist_count === 1){
														$err_column_array['error']["$shift_date_col_name$row"] = "Already Reached Maximum Forgot Punch Count for this Salary Month..!Please Check?";
														$exist_count++;
													}
												}
											}
											$shift_name        = (int)$shift_details_arr[$employee_code][$shift_date]['shift_id'];
											$from_time         = $shift_details_arr[$employee_code][$shift_date]['from_time'];
											$to_time           = $shift_details_arr[$employee_code][$shift_date]['to_time'];
											$first_half        = $shift_details_arr[$employee_code][$shift_date]['first_half'];
											$second_half       = $shift_details_arr[$employee_code][$shift_date]['second_half'];
											$shift_status      = (int)$shift_details_arr[$employee_code][$shift_date]['shift_status'];
											$shift_start       = (int)$shift_details_arr[$employee_code][$shift_date]['shift_start'];
											$shift_end         = (int)$shift_details_arr[$employee_code][$shift_date]['shift_end'];
											$import_in_time    = $shift_details_arr[$employee_code][$shift_date]['in_time'];
											$import_out_time   = $shift_details_arr[$employee_code][$shift_date]['out_time'];
											$half_work_hour    = date('H:i:s', strtotime($shift_details_arr[$employee_code][$shift_date]['half_work_hour']));
											$full_work_hour    = date('H:i:s', strtotime($shift_details_arr[$employee_code][$shift_date]['full_work_hour']));

											$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($date_type === 1){
												if($shift_first_half <= $in_date_time || $import_in_date > $in_date_time){	
													(int)$exist_count += 1;
													if($exist_count === 1){
														$err_column_array['error']["$in_date_col_name$row"] = "Please Map Correct In Date or In Time..!!";
														$exist_count++;
													}
												}else
												if($shift_second_half >= $out_date_time || $import_out_date < $out_date_time){
													(int)$exist_count += 1;
													if($exist_count === 1){
														$err_column_array['error']["$out_date_col_name$row"] = "Please Map Correct Out Date or Out Time..!!";
														$exist_count++;
													}
												}else
												if($full_work_hour > $total_time){
													(int)$exist_count += 1;
													if($exist_count === 1){
														$err_column_array['error']["$out_date_col_name$row"] = "Total Time should not Lesser than Full Day Work Hours..!!";
														$exist_count++;
													}
												}else{
													$check_validation = true; 
												}
											}else
											if($date_type === 2){
												if($shift_first_half <= $in_date_time || $import_in_date > $in_date_time){
													(int)$exist_count += 1;
													if($exist_count === 1){
														$err_column_array['error']["$in_date_col_name$row"] = "Please Map Correct In Date or In Time..!!";
														$exist_count++;
													}
												}else
												if($shift_form_date >= $out_date_time || $shift_to_date <= $out_date_time || $import_out_date < $out_date_time){
													(int)$exist_count += 1;
													if($exist_count === 1){
														$err_column_array['error']["$out_date_col_name$row"] = "Please Map Correct Out Date or Out Time..!!";
														$exist_count++;
													}
												}else
												if($half_work_hour > $total_time){
													(int)$exist_count += 1;
													if($exist_count === 1){
														$err_column_array['error']["$out_date_col_name$row"] = "Total Time should not Lesser than Half Day Work Hours..!!";
														$exist_count++;
													}
												}else{
													$check_validation = true; 
												}
											}
											else{
												// if($shift_from_date >= $in_date_time || $shift_to_date <= $in_date_time || $import_in_date > $in_date_time){
												// 	(int)$exist_count += 1;
												// 	if($exist_count === 1){
												// 		$err_column_array['error']["$in_date_col_name$row"] = "Please Map Correct In Date or In Time..!!";
												// 		$exist_count++;
												// 	}
												// }else
												// if($shift_second_half >= $out_date_time || $import_out_date < $out_date_time){
												// 	(int)$exist_count += 1;
												// 	if($exist_count === 1){
												// 		$err_column_array['error']["$out_date_col_name$row"] = "Please Map Correct Out Date or Out Time..!!";
												// 		$exist_count++;
												// 	}
												// }else
												// if($half_work_hour > $total_time){
												// 	(int)$exist_count += 1;
												// 	if($exist_count === 1){
												// 		$err_column_array['error']["$out_date_col_name$row"] = "Total Time should not Lesser than Half Day Work Hours..!!";
												// 		$exist_count++;
												// 	}
												// }else{
												// 	$check_validation = true; 
												// }	
												$check_validation = true; 
											}
											if((int)$check_validation === 1){
												$prime_time_id      = $time_entry_arr[$employee_code][$shift_date]['prime_time_entry_id'];
												$entry_flag         = $time_entry_arr[$employee_code][$shift_date]['entry_flag'];
												$update_flag         = $time_entry_arr[$employee_code][$shift_date]['update_flag'];
												$first_half_status  = $time_entry_arr[$employee_code][$shift_date]['first_half_status'];
												$first_half_count   = $time_entry_arr[$employee_code][$shift_date]['first_half_count'];
												$second_half_status = $time_entry_arr[$employee_code][$shift_date]['second_half_status'];
												$second_half_count  = $time_entry_arr[$employee_code][$shift_date]['second_half_count'];
												$day_type           = $time_entry_arr[$employee_code][$shift_date]['whole_day_status'];
												$check_day_type     = (int)$day_status_legend_arr[$day_type]['day_type'];
												//TIME ENTRY CHECK VALIDATION
												if($day_type === "W" || $day_type === "U"){//weekoff and unpunch tag only for update
													if($check_day_type === 1){
														if($date_type === 1){
															$entry_flag         = "M";
															$whole_day_status   = "M";
															$first_half_status  = "MP";
															$second_half_status = "MP";
															$first_half_count   = 0.5;
															$second_half_count  = 0.5;
														}else
														if($date_type === 2){
															if($day_type === "W"){
																$update_flag    = "W";
															}else
															if($day_type === "U"){
																$update_flag    = "U";
															}
															$entry_flag         = "M";
															$whole_day_status   = "$entry_flag"."$update_flag";
															$first_half_status  = "MP";
															$first_half_count   = 0.5;
														}else
														if($date_type === 3){
															if($day_type === "W"){
																$update_flag    = "W";
															}else
															if($day_type === "U"){
																$update_flag    = "U";
															}
															$entry_flag         = "M";
															$whole_day_status   = "$update_flag"."$entry_flag";
															$second_half_status = "MP";
															$second_half_count  = 0.5;
														}
														//UPD QUERY VALUE
														$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_name.'","'.$in_date_time.'","'.$out_date_time.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
													}
												}else//for full day OR same day type check false
												if($check_day_type === 1 || $check_day_type === $date_type){
													(int)$exist_count += 1;
													if($exist_count === 1){
														$err_column_array['error']["$shift_date_col_name$row"] = "Already Exist in Attendance Entry..!!";
														$exist_count++;
													}
												}else
												if(($check_day_type !== $date_type) && $entry_flag){
													if($date_type === 1){
														(int)$exist_count += 1;
														if($exist_count === 1){
															$err_column_array['error']["$shift_date_col_name$row"] = "Already Exist in Attendance Entry..!!";
															$exist_count++;
														}
													}else{
														$update_flag  = "M";
														//for 1st half update
														if($check_day_type === 3){
															if($date_type === 2){
																$first_half_status  ="MP";
																$whole_day_status   = "$update_flag"."$entry_flag";
																$first_half_count   = 0.5;
															}
														}
														//for 2nd half update
														else
														if($check_day_type === 2){
															if($date_type === 3){
																$second_half_status = "MP";
																$whole_day_status   = "$entry_flag"."$update_flag";
																$second_half_count  = 0.5;
															}
														}	
														//UPD QUERY VALUE
														$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_name.'","'.$in_date_time.'","'.$out_date_time.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
													}
												}else{//for full day insert
													$entry_flag     = "M";
													if($date_type === 1){
														$whole_day_status   = "M";
														$first_half_status  = "MP";
														$second_half_status = "MP";
				
														$first_half_count   = 0.5;
														$second_half_count  = 0.5;
													}
													else//for 1st half insert
													if($date_type === 2){
														$whole_day_status   = "FM";
														$first_half_status  = "MP";
														$first_half_count   = 0.5;
														$second_half_status = "";
														$second_half_count  = "";
													}
													else//for 2nd half insert
													if($date_type === 3){
														$whole_day_status   = "SM";
														$second_half_status = "MP";
														$first_half_status  = "";
														$first_half_count   = "";
														$second_half_count  = 0.5;
													}
													//INSERT QUERY VALUE
													$time_entry_ins_value .= '("'.$employee_code.'","'.$shift_name.'","'.$shift_date.'","'.$entry_flag.'","'.$whole_day_status.'","'.$in_date_time.'","'.$out_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
												}
												//array for check a same excel exist check
												$excel_exist_arr[$employee_code][$shift_date] = $shift_date;

												$prime_query_value .= '"'.$category.'","'.$employee_code.'","'.$shift_name.'","'.$shift_date.'","'.$in_date.'","'.$out_date.'","'.$in_time.'","'.$out_time.'","'.$total_time.'","'.$date_type.'","2","'.$mp_reason.'","'.$prime_financial_id.'","'.$this->logged_id.'","'.$created_on.'"),(';
								
												$status_info['Status'] = "Inserted to DB";
												$status_array[] = $status_info;
												$excel_post_data[$row] = $post_data_arr;
											}
										}	
									}
								}
							}	
						}else{
							(int)$exist_count += 1;
							if($exist_count === 1){
								$err_column_array['error']["$row"] = "please Map All Excel Column Data..!";
								$exist_count++;
							}
						}
					}
					$err_column_count = count($err_column_array['error'] ?? []);
					if((int)$err_column_count > 0){
						$table_info = $this->get_excel_error_ui($err_column_array);
						echo json_encode(array('success'=>false,'message'=>"Data Not Imported",'table_info'=>$table_info));
					}else{
						$rslt = false;
						$time_entry_upd_value  = rtrim($time_entry_upd_value,",");
						$time_entry_ins_value  = rtrim($time_entry_ins_value,",");
						$prime_query_value     = rtrim($prime_query_value,",");
						if($time_entry_upd_value || $time_entry_ins_value){
							if($prime_query_value){
								$prime_column_val = "component_value,employee_code,shift_name,shift_date,in_date,out_date,in_time,out_time,total_time,day_type,leave_status,mp_reason,financial_setting_id,trans_created_by,trans_created_date";
								$prime_query_value = rtrim($prime_query_value,"),(");	
								$prime_query   = "insert into $this->prime_table ($prime_column_val) VALUES ($prime_query_value)";			 			
								$insert_info   = $this->db->query($prime_query);

								if($insert_info){									
									$leave_status   = 2;									
									$leave_financial_info  = $this->get_leave_financial_details();
									$prime_financial_id    = $leave_financial_info[0]->prime_leave_financial_year_id;
									if((int)$mp_treat_time_log === 1){
										$time_log_rslt    = $this->time_log_insert($excel_post_data,$prime_financial_id,$leave_status);
										$success          = $time_log_rslt['success'];
									}else{
										$time_entry_upd_info      = "";
										$time_entry_ins_info      = "";
										if($time_entry_upd_value){
											//BULK UPDATE TO TIME ENTRY
											$time_entry_upd_qry     = 'INSERT INTO cw_time_entry (prime_time_entry_id,shift_id,manual_in,manual_out,entry_flag,update_flag,whole_day_status,first_half_status,first_half_count,second_half_status,second_half_count,trans_updated_by,trans_updated_date) VALUES '.$time_entry_upd_value.' ON DUPLICATE KEY UPDATE shift_id = VALUES(shift_id),manual_in = VALUES(manual_in),manual_out = VALUES(manual_out),entry_flag = VALUES(entry_flag),update_flag = VALUES(update_flag),whole_day_status = VALUES(whole_day_status),first_half_status = VALUES(first_half_status),first_half_count = VALUES(first_half_count),second_half_status = VALUES(second_half_status),second_half_count = VALUES(second_half_count),trans_updated_by = VALUES(trans_updated_by),trans_updated_date = VALUES(trans_updated_date)';
											$time_entry_upd_info    = $this->db->query($time_entry_upd_qry);
										}
										//INSERT TO TIME ENTRY
										if($time_entry_ins_value){
											$time_entry_ins_qry     = 'INSERT INTO cw_time_entry (employee_code,shift_id,att_date,entry_flag,whole_day_status,manual_in,manual_out,first_half_status,first_half_count,second_half_status,second_half_count,trans_created_by,trans_created_date) VALUES '.$time_entry_ins_value.'';
											$time_entry_ins_info    = $this->db->query("CALL sp_a_run ('RUN','$time_entry_ins_qry')");
										}
									}
									
									// if($time_entry_upd_info || $time_entry_ins_info){									
										$table_info = $this->get_excel_import_ui($status_array);
										return json_encode(array('success'=>true,'message'=>"Successfully File Imported",'table_info'=>$table_info));
									// }
								}
							}
						}
					}
				}
			}
		}
	}

	// public function do_excel_manual_punch_import($import_id,$category,$process_month){
	// 	$leave_financial_info  = $this->get_leave_financial_details();
	// 	$prime_financial_id    = $leave_financial_info[0]->prime_leave_financial_year_id;
	// 	$starting_date         = date('Y-m-d',strtotime($leave_financial_info[0]->starting_date));	
	// 	$ending_date           = date('Y-m-d',strtotime($leave_financial_info[0]->ending_date));	
	// 	//CATEGORY BASED SALARY START DATE AND END DATE DETAILS
	// 	$salary_info_arr       = $this->salary_start_end_info($category,$process_month);

	// 	$salary_start_date     = date('Y-m-d',strtotime($salary_info_arr['salary_start_date']));
	// 	$salary_end_date       = date('Y-m-d',strtotime($salary_info_arr['salary_end_date']));	
	// 	$emp_name_arr          = "";
	// 	$time_entry_arr        = "";
	// 	$leave_entry_arr       = "";
	// 	$shift_request_arr     = "";
	// 	$shift_import_arr      = "";
	// 	$man_punch_exist_arr   = "";
	// 	$filename              = dirname(__FILE__)."/php_excel/PHPExcel/IOFactory.php";
	// 	include($filename);
	// 	if($import_id < 0){
	// 		return json_encode(array('success' => false, 'message' => "Invalid file upload"));
	// 	}		
	// 	$excel_path_qry    = 'select * from cw_import where import_id = "'.$import_id.'"';
	// 	$excel_path_info   = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
	// 	$excel_path_result = $excel_path_info->result();
	// 	$excel_path_info->next_result();
		
	// 	if(!$excel_path_result){
	// 		return json_encode(array('success' => false, 'message' => "Invalid file upload"));
	// 	}else{
	// 		$excel_file_path    = $excel_path_result[0]->excel_file_path;
	// 		$module_id          = $excel_path_result[0]->module_id;
	// 		$excel_format       = $excel_path_result[0]->excel_format;
	// 		$excel_sheet_name   = (int)$excel_path_result[0]->excel_sheet_name;
	// 		$excel_row_start    = (int)$excel_path_result[0]->excel_start_row;
	// 		$excel_row_end      = (int)$excel_path_result[0]->excel_end_row;
			
	// 		$format_qry 	= 'select * from cw_util_excel_format where prime_excel_format_id = "'.$excel_format.'" and cw_util_excel_format.trans_status = 1';
	// 		$format_info    = $this->db->query("CALL sp_a_run ('SELECT','$format_qry')");
	// 		$format_rslt    = $format_info->result();
	// 		$format_info->next_result();
			
	// 		if(!$format_rslt){
	// 			return json_encode(array('success' => false, 'message' => "Please add excel format before import"));
	// 		}else{
	// 			//function for get a last payroll processed date
	// 			//GET EMPLOYEE NAME FROM EMPLOYEE MASTER
	// 			$emp_name_qry      = 'select employee_code,emp_name,date_of_joining from cw_employees where trans_status = 1 and (cw_employees.termination_status = 0 or cw_employees.resignation_date >= "'.$salary_start_date.'")';
	// 			$emp_name_info     = $this->db->query("CALL sp_a_run ('RUN','$emp_name_qry')");
	// 			$emp_name_result   = $emp_name_info->result_array();
	// 			$emp_name_info->next_result();

	// 			$emp_name_arr      = array_reduce($emp_name_result, function ($result, $arr) {
	// 			    $result[$arr['employee_code']]= $arr;
	// 			    return $result;
	// 			}, array());	
				
	// 			//SHIFT REQUEST STATUS ARRAY
	// 			$shift_request_qry    = 'SELECT cw_request.employee_code,cw_request.shift_date FROM cw_request WHERE cw_request.employee_code = "'.$employee_code.'" and cw_request.request_type = "6" and cw_request.leave_status in (1,2) and cw_request.shift_date >= "'.$salary_start_date.'" and financial_setting_id = "'.$financial_year_id.'" and trans_status = 1';
	// 			$shift_request_info   = $this->db->query("CALL sp_a_run ('SELECT','$shift_request_qry')");
	// 			$shift_request_rslt   = $shift_request_info->result_array();
	// 			$shift_request_info->next_result();

	// 			$shift_request_arr    = array_reduce($shift_request_rslt, function ($result, $arr) {
	// 			    $result[$arr['employee_code']][$arr['shift_date']] = $arr['shift_date'];
	// 			    return $result;
	// 			}, array());

	// 			//QUERY FOR CHECK EXIST DATA FROM LEAVE ENTRY TABLE 
	// 			$leave_entry_qry    = 'select employee_code,leave_date from cw_leave_entry where trans_status = 1 and leave_status NOT IN (3,4) and financial_setting_id = "'.$prime_financial_id.'" and cw_leave_entry.leave_date >= "'.$salary_start_date.'"';
	// 			$leave_entry_info   = $this->db->query("CALL sp_a_run ('RUN','$leave_entry_qry')");
	// 			$leave_entry_result = $leave_entry_info->result_array();
	// 			$leave_entry_info->next_result();

	// 			$leave_entry_arr    = array_reduce($leave_entry_result, function ($result, $arr) {
	// 			    $result[$arr['employee_code']][$arr['leave_date']] = $arr['leave_date'];
	// 			    return $result;
	// 			}, array());

	// 			//QUERY FOR CHECK EXIST DATA FROM TIME ENTRY TABLE 
	// 			$time_entry_qry     = 'select from cw_time_entry where trans_status = 1 and cw_time_entry.att_date >= "'.$salary_start_date.'"';
	// 			$time_entry_info    = $this->db->query("CALL sp_a_run ('RUN','$time_entry_qry')");
	// 			$time_entry_result  = $time_entry_info->result_array();
	// 			$time_entry_info->next_result();

	// 			$time_entry_arr     = array_reduce($time_entry_result, function ($result, $arr) {
	// 			    $result[$arr['employee_code']][$arr['att_date']] = $arr;
	// 			    return $result;
	// 			}, array());

	// 			//QUERY FOR CHECK EXIST DATA FROM SHIFT IMPORT TABLE 
	// 			$shift_import_exist_qry    = 'select (*),prime_shift_import_id,cw_shift_import.employee_code,cw_shift_import.shift_date,cw_shift_import.shift_name from cw_shift_master inner join cw_shift_import on cw_shift_import.shift_name = cw_shift_master.prime_shift_master_id where cw_shift_import.shift_date >= "'.$salary_start_date.'" and cw_shift_import.financial_setting_id ="'.$prime_financial_id.'" and  cw_shift_import.trans_status = 1,cw_shift_master.trans_status = 1';
	// 			$shift_import_exist_info   = $this->db->query("CALL sp_a_run ('RUN','$shift_import_exist_qry')");
	// 			$shift_import_exist_result = $shift_import_exist_info->result_array();
	// 			$shift_import_exist_info->next_result();

	// 			$shift_master_import_arr   = array_reduce($shift_import_exist_result, function ($result, $arr) {
	// 			    $result[$arr['employee_code']][$arr['shift_date']] = $arr;
	// 			    return $result;
	// 			}, array());

	// 			//QUERY FOR CHECK EXIST DATA FROM MANUAL PUNCH ENTRY TABLE 
	// 			$man_punch_exist_qry  = 'select * from cw_manual_punch_entry where financial_setting_id ="'.$prime_financial_id.'" and cw_manual_punch_entry.leave_status in (1,2) and cw_manual_punch_entry.in_date >= "'.$salary_start_date.'" and trans_status = 1';
	// 			$man_punch_exist_info = $this->db->query("CALL sp_a_run ('RUN','$man_punch_exist_qry')");
	// 			$man_punch_exist_rslt = $man_punch_exist_info->result_array();
	// 			$man_punch_exist_info->next_result();

	// 			$man_punch_exist_arr  = array_reduce($man_punch_exist_rslt, function ($result, $arr){
	// 			    $result[$arr['employee_code']][$arr['in_date']] = $arr['day_type'];
	// 			    return $result;
	// 			}, array());	
				
	// 			$exist_column_name  = explode(",",$format_rslt[0]->exist_column_name);
	// 			$excel_format_qry 	= 'select field_type,pick_table,pick_list_type,pick_list_import,pick_list,mandatory_field,field_isdefault,excel_line_column_name,excel_line_value from cw_util_excel_format_line inner join cw_form_setting on label_name = excel_line_column_name where excel_line_module_id = "'.$module_id.'" and prime_excel_format_id = "'.$excel_format.'" and cw_form_setting.prime_module_id = "'.$module_id.'" and cw_util_excel_format_line.trans_status = 1 ORDER BY cw_util_excel_format_line.excel_line_value ASC';			
	// 			$excel_format        = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
	// 			$excel_format_result = $excel_format->result();
	// 			$excel_format->next_result();

	// 			if(!$excel_format_result){
	// 				return json_encode(array('success' => false, 'message' => "Please map excel cell column before import"));
	// 			}else{
	// 				try{
	// 					$excel_obj = \PhpOffice\PhpSpreadsheet\IOFactory::load($excel_file_path);
	// 				}catch(Exception $e){
	// 					die('Error loading file "' . pathinfo($excel_file_path, PATHINFO_BASENAME). '": ' . $e->getMessage());
	// 					return json_encode(array('success' => false, 'message' => "Invalid file or path"));
	// 				}
	// 				$sheet           = $excel_obj->getSheet($excel_sheet_name);
	// 				if($excel_row_end){
	// 					$total_rows = $excel_row_end;
	// 				}else{
	// 					$total_rows = $sheet->getHighestRow();
	// 				}
	// 				$highest_column          = $sheet->getHighestColumn();
	// 				$worksheetTitle          = $sheet->getTitle();
	// 				$status_array	         = array();
	// 				$leave_creation_arr      = array();
	// 				$opening_used_arr        = array();
	// 				$opening_arr	         = array(); 
	// 				$weekoff_excel_exist_arr = array();
	// 				$prime_query_value       = "";
	// 				$prime_upd_query_value   = "";

	// 				for($row =$excel_row_start; $row <= $total_rows; $row++) {
	// 					$prime_column_val = "";
	// 					$prime_cell_val   = "";
	// 					$exist_val        = "";
	// 					$status_info = array();
	// 					$status_info["Excel Row"] = $row;
	// 					$sts = TRUE;
	// 					$email_sts = TRUE;
	// 					foreach($excel_format_result as $excel_info){
	// 						$field_isdefault        = (int)$excel_info->field_isdefault;
	// 						$mandatory_field        = (int)$excel_info->mandatory_field;
	// 						$field_type             = (int)$excel_info->field_type;
	// 						$pick_table             = $excel_info->pick_table;
	// 						$pick_list_type         = (int)$excel_info->pick_list_type;
	// 						$pick_list_import       = (int)$excel_info->pick_list_import;
	// 						$pick_list              = $excel_info->pick_list;
	// 						$excel_line_column_name = $excel_info->excel_line_column_name;
	// 						$excel_line_value       = $excel_info->excel_line_value;

	// 						$get_cell_value         = ucwords(trim($sheet->getCell("$excel_line_value$row")->getValue()));
    //                         if($get_cell_value){
	// 							//FOR MOBILE NUMBER
	// 							 if($field_type === 11){
	// 								$length = strlen($get_cell_value);
	// 								$length_query = 'select field_length from cw_form_setting where cw_form_setting.prime_module_id = "'.$module_id.'" and cw_form_setting.field_type = 11';
	// 								$length_data  = $this->db->query("CALL sp_a_run ('SELECT','$length_query')");
	// 								$length_result = $length_data->result();
	// 								$length_data->next_result();
	// 								$field_length = $length_result[0]->field_length;
	// 								if($field_length != $length){
	// 									$sts = FALSE;
	// 								}
	// 							}else 
	// 							if($field_type === 12){
	// 								//FOR EMAIL
	// 								$email = $get_cell_value;
	// 								if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
	// 									$email_sts = FALSE;
	// 								}
	// 							}else
	// 							if($field_type === 4){
	// 								// FOR DATE
	// 								$get_cell_value   = trim(Date::excelToDateTimeObject((int)$sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));
	// 								$format           = "Y-m-d";

	// 								$date             = DateTime::createFromFormat($format , $get_cell_value);

	// 								$date_format_sts  = $date && $date->format($format) === $get_cell_value;
	// 								if(!$date_format_sts){
	// 									$err_column_array['error']["$excel_line_value$row"]   = "Invalid Date Format..Please Map Date Format like (DD/MM/YYYY)..!";
	// 								}else
	// 								if(($salary_start_date > $get_cell_value) || ($salary_end_date < $get_cell_value)){
	// 									$err_column_array['error']["$excel_line_value$row"]   = "Invalid Date Format..Please Map Date Format like (DD/MM/YYYY) or Your In Date and Out Date in Between Salary Date..!";
	// 								}
	// 							}else
	// 							if($field_type === 13){
	// 								$get_cell_value = trim(date('Y-m-d H:i:s',Date::PHPToExcel($sheet->getCell("$excel_line_value$row")->getValue())));
	// 							}else
	// 							// FOR PICKLIST CHECK
	// 							if(($field_type === 5) || ($field_type === 7)){
	// 								if($pick_list_type === 1){
	// 									$pick_list_val   = explode(",",$pick_list);
	// 									$pick_list_val_1 = $pick_list_val[0];
	// 									$pick_list_val_2 = $pick_list_val[1];
	// 									$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
	// 									if($pick_list_import === 1){
	// 										$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_1.' = "'.$get_cell_value.'"';	
	// 									}else{
	// 										$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
	// 									}	
	// 									$pick_data  = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
	// 									$pick_result = $pick_data->result();
	// 									$pick_count  = $pick_data->num_rows();
	// 									$pick_data->next_result();
	// 									if((int)$pick_count === 0){
	// 										$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
	// 									}else
	// 									if((int)$pick_count === 1){
	// 										if($pick_table !== $this->prime_table){
	// 											$pick_id     = $pick_result[0]->$pick_list_val_1;
	// 											$pick_status = (int)$pick_result[0]->trans_status;
	// 											if($pick_status === 0){
	// 												$upd_query  = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = '.$pick_id;
	// 												$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
	// 											}
	// 											$get_cell_value = $pick_id;
	// 										}
	// 									}
	// 								}else
	// 								if($pick_list_type === 2){
	// 									$pick_list_val_1 = $pick_table."_id";
	// 									$pick_list_val_2 = $pick_table."_value";
	// 									$pick_list_val_3 = $pick_table."_status";
	// 									$pick_query = 'select * from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
	// 									$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
	// 									$pick_result = $pick_data->result();
	// 									$pick_count  = $pick_data->num_rows();
	// 									$pick_data->next_result();
	// 									if((int)$pick_count === 0){
	// 										$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
	// 									}else
	// 									if((int)$pick_count === 1){
	// 										$pick_id     = $pick_result[0]->$pick_list_val_1;
	// 										$pick_status = (int)$pick_result[0]->$pick_list_val_3;
	// 										if($pick_status === 0){
	// 											$upd_query  = 'update '.$pick_table.' set '.$pick_list_val_3.' = 1 where '.$pick_list_val_1.' = '.$pick_id;
	// 											$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
	// 										}
	// 										$get_cell_value = $pick_id;
	// 									}
	// 								}
	// 							}
	// 							if($field_isdefault === 1){
	// 								if($excel_line_column_name === 'employee_code'){
	// 									$emp_code_col_name  = $excel_line_value;
	// 									$employee_code      = $get_cell_value;
	// 									$employee_name      = $emp_name_arr[$employee_code]['emp_name'];
	// 									$check_emp_code     = $emp_name_arr[$employee_code]['employee_code'];
	// 									if(!$check_emp_code){
	// 										$err_column_array['error']["$excel_line_value$row"] = "This Employee Code ($employee_code) or Employee Name not Present in the Employee Master? Please Check it..!";
	// 									}
	// 								}else
	// 								if($excel_line_column_name === "shift_name"){
	// 									$shift_name           = $get_cell_value;
	// 								}else
	// 								if($excel_line_column_name === "in_date"){
	// 									$shift_date_col_name  = $excel_line_value;
	// 									$in_date              = $get_cell_value;
	// 								}else
	// 								if($excel_line_column_name === "out_date"){
	// 									$out_date             = $get_cell_value;
	// 									$after_out_date       = date('Y-m-d',strtotime("+1 day",strtotime($out_date)));
	// 								}else
	// 								if($excel_line_column_name === "in_time"){
	// 									$in_time              = date('H:i',strtotime($get_cell_value)); 
	// 								}else
	// 								if($excel_line_column_name === "out_time"){
	// 									$out_time             = date('H:i',strtotime($get_cell_value)); 
	// 									$total_time           = $this->total_time_cal($in_date,$out_date,$in_time,$out_time,$in_time_count,$out_time_count);
	// 									if(!$total_time){
	// 										$err_column_array['error']["$excel_line_value$row"] = "Please Map a Correct In Time or Out Time..!";
	// 									}
	// 								}else
	// 								if($excel_line_column_name === "day_type"){
	// 									$day_type_col_name  = $excel_line_value;
	// 									$day_type           = (int)$get_cell_value; 
	// 								}
	// 								else
	// 								if($excel_line_column_name === "mp_reason"){
	// 									$mp_reason          = (int)$get_cell_value; 
	// 								}
									
	// 								if(empty($exist_column_name)){
	// 									 if($mandatory_field === 1){
	// 										$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
	// 									}
	// 								}else{
	// 									if(in_array($excel_line_column_name,$exist_column_name)){
	// 										$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
	// 									}
	// 								}
	// 							}
	// 						}
	// 					}
	// 					if($employee_code && $employee_name && $shift_name && $in_date && $out_date && $in_time && $out_time && $total_time && $day_type){
	// 						$period = new DatePeriod(
	// 						    new DateTime("$in_date"),
	// 						    new DateInterval('P1D'),
	// 						    new DateTime("$after_out_date")
	// 						);
	// 					}
	// 					$created_on  = date("Y-m-d H:i:s");
	// 					$exist_count = 0;
	// 					foreach ($period as $key => $value) {
	// 						$punch_date             = $value->format('Y-m-d');
	// 						//GET EMLOYEE DATE OF JOINING
	// 						$emp_doj               = $emp_name_arr[$employee_code]['date_of_joining'];
	// 						//CHECK SHIFT REQUEST DATE IN REQUEST MODULE
	// 						$shift_request_date    = $shift_request_arr[$employee_code][$punch_date];
							
	// 						//CONDITION FOR CHECK A LEAVE ENTRY EXIST IF EXIST NOT UPDATE TO SHIFT IMPORT
	// 						$check_leave_entry     = $leave_entry_arr[$employee_code][$punch_date];

	// 						//CHECK ALREADY EXIST MANUAL PUNCH DEATILS
	// 						$exist_punch_day_type  = (int)$man_punch_exist_arr[$employee_code][$punch_date];

	// 						//SHIFT IMPORT CHECK PROCESS
	// 						$shift_import_name     = $shift_master_import_arr[$employee_code][$punch_date]['shift_name'];
	// 						$shift_status          = $shift_master_import_arr[$employee_code][$punch_date]['shift_status'];

	// 						//CONDITION FOR CHECK A TIME ENTRY EXIST IF EXIST NOT UPDATE TO SHIFT IMPORT
	// 						// $check_time_entry   = $time_entry_arr[$employee_code][$punch_date];

	// 						if($emp_doj > $punch_date){
	// 							(int)$exist_count += 1;
	// 							if($exist_count === 1){
	// 								$err_column_array['error']["$shift_date_col_name$row"] = "Shift Date Should not be Greater than Date of Joining Please Check it..!!";
	// 								$exist_count++;
	// 							}
	// 						}else
	// 						if($shift_request_date){
	// 							(int)$exist_count += 1;
	// 							if($exist_count === 1){
	// 								$err_column_array['error']["$shift_date_col_name$row"] = "In this Date Shift Request was Pending Please Check it..!!";
	// 								$exist_count++;
	// 							}
	// 						}else
	// 						if($check_leave_entry){
	// 							(int)$exist_count += 1;
	// 							if($exist_count === 1){
	// 								$err_column_array['error']["$shift_date_col_name$row"] = "In this Date Already Leave Request Exist Please Check it..!!";
	// 								$exist_count++;
	// 							}
	// 						}else//for check valid shift import or not to check from shift import array
	// 						if($shift_import_name !== $shift_name){
	// 							(int)$exist_count += 1;
	// 							//IF CHECK COUNT === 1 FOR SAME EXCEL ROW(FROM AND TO DATE PERIOD)
	// 							if($exist_count === 1){
	// 								$shift_date = $value->format('d-m-Y');
	// 								$err_column_array['error']["$shift_date_col_name$row"] = "Please Map Correct Shift Name for this Date of $shift_date";
	// 								$exist_count++;
	// 							}
	// 						}else
	// 						if($exist_punch_day_type){
	// 							(int)$exist_count += 1;
	// 							//IF CHECK COUNT === 1 FOR SAME EXCEL ROW(FROM AND TO DATE PERIOD)
	// 							if($exist_count === 1){
	// 								$shift_date = $value->format('d-m-Y');
	// 								$err_column_array['error']["$shift_date_col_name$row"] = "Already Exist in Manual Punch Entry for this Shift Date of $shift_date";
	// 								$exist_count++;
	// 							}	
	// 						}else{
	// 							$prime_query_value .= '"'.$category.'","'.$employee_code.'","'.$shift_name.'","'.$in_date.'","'.$out_date.'","'.$in_time.'","'.$out_time.'","'.$total_time.'","'.$day_type.'","2","'.$mp_reason.'","'.$prime_financial_id.'","'.$this->logged_id.'","'.$created_on.'"),(';
								
	// 							$status_info['Status'] = "Inserted to DB";
	// 							$status_array[] = $status_info;
	// 						}	
	// 					} 
	// 				}
	// 				$err_column_count = count($err_column_array['error']);
	// 				if((int)$err_column_count > 0){
	// 					$table_info = $this->get_excel_error_ui($err_column_array);
	// 					echo json_encode(array('success'=>false,'message'=>"Data Not Imported",'table_info'=>$table_info));

	// 				}else{
	// 					$rslt = false;
	// 					if($prime_query_value){
	// 						$prime_column_val = "category,employee_code,shift_name,in_date,out_date,in_time,out_time,total_time,day_type,leave_status,mp_reason,financial_setting_id,trans_created_by,trans_created_date";
	// 						$prime_query_value = rtrim($prime_query_value,"),(");	
	// 						$prime_query   = "insert into $this->prime_table ($prime_column_val) VALUES ($prime_query_value)";						
	// 						$insert_info   = $this->db->query($prime_query);
	// 						$rslt = true;
	// 					}
	// 					if($rslt){
	// 	                    $table_info = $this->get_excel_import_ui($status_array);
	// 						return json_encode(array('success'=>true,'message'=>"Successfully File Imported",'table_info'=>$table_info));
	// 					}else{
	// 						return json_encode(array('success'=>true,'message'=>" File Not Imported",'table_info'=>$table_info));
	// 					}
	// 				}
	// 			}
	// 		}
	// 	}
	// }

	//Update Leave Opening Used Leaves
	public function update_used_leave($opening_arr,$opening_balance_used_arr,$prime_financial_id){
		$created_on = date("Y-m-d h:i:s");
		foreach ($opening_arr as $emp_code => $leave_arr) {
			$upd_qry = "";
			foreach ($leave_arr as $leave_name => $value){
				$leave_key = "used_".$leave_name;
				$prev = $opening_balance_used_arr[$emp_code][$leave_key];
				$leave_count = $prev + $value;
				$upd_qry .= $leave_key.'="'.$leave_count.'",';
			}
			if($upd_qry){
				$upd_qry  .=  'trans_updated_by = "'.$logged_id.'", trans_updated_date = "'.$created_on.'"';
				$upd_qry  = 'UPDATE cw_leave_opening SET '.$upd_qry.' WHERE employee_code = "'.$emp_code.'" and financial_setting_id = "'.$prime_financial_id.'"';
				$upd_info = $this->db->query("CALL sp_a_run ('RUN','$upd_qry')");	
			}
		}
		if($upd_info){
			return true;
		}
	}
	//IMPORT DATA FROM FILE PATH
	public function do_excel_import($import_id,$import_type){
		if($import_id < 0){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}
		
		$excel_path_qry    = 'select * from cw_import where import_id = "'.$import_id.'"';
		$excel_path_info   = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
		$excel_path_result = $excel_path_info->result();
		$excel_path_info->next_result();
		if(!$excel_path_result){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}else{
			$excel_file_path    = $excel_path_result[0]->excel_file_path;
			$module_id          = $excel_path_result[0]->module_id;
			$excel_format       = $excel_path_result[0]->excel_format;
			$excel_sheet_name   = (int)$excel_path_result[0]->excel_sheet_name;
			$excel_row_start    = (int)$excel_path_result[0]->excel_start_row;
			$excel_row_end      = (int)$excel_path_result[0]->excel_end_row;
			
			$format_qry 	= 'select * from cw_util_excel_format where prime_excel_format_id = "'.$excel_format.'" and cw_util_excel_format.trans_status = 1';
			$format_info    = $this->db->query("CALL sp_a_run ('SELECT','$format_qry')");
			$format_rslt    = $format_info->result();
			$format_info->next_result();
			if(!$format_rslt){
				return json_encode(array('success' => false, 'message' => "Please add excel format before import"));
			}else{
				$exist_column_name = explode(",",$format_rslt[0]->exist_column_name);
				$excel_format_qry 	= 'select field_type,pick_table,pick_list_type,pick_list_import,pick_list,mandatory_field,field_isdefault,excel_line_column_name,excel_line_value,label_name,view_name,unique_field from cw_util_excel_format_line inner join cw_form_setting on label_name = excel_line_column_name where excel_line_module_id = "'.$module_id.'" and prime_excel_format_id = "'.$excel_format.'" and cw_form_setting.prime_module_id = "'.$module_id.'" and cw_util_excel_format_line.trans_status = 1';			
				$excel_format        = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
				$excel_format_result = $excel_format->result();
				$excel_format->next_result();
				if(!$excel_format_result){
					return json_encode(array('success' => false, 'message' => "Please map excel cell column before import"));
				}else{
					try{
						$excel_obj = \PhpOffice\PhpSpreadsheet\IOFactory::load($excel_file_path);
					}catch(Exception $e){
						die('Error loading file "' . pathinfo($excel_file_path, PATHINFO_BASENAME). '": ' . $e->getMessage());
						return json_encode(array('success' => false, 'message' => "Invalid file or path"));
					}
					$sheet           = $excel_obj->getSheet($excel_sheet_name);
					if($excel_row_end){
						$total_rows = $excel_row_end;
					}else{
						$total_rows = $sheet->getHighestRow();
					}
					$highest_column  = $sheet->getHighestColumn();
					$worksheetTitle  = $sheet->getTitle();

					//Unique field check
					$err_column_tabview  = array();
					$array_uniq 		= array();
					foreach ($excel_format_result as $key => $value) {
						$label_name 		= $value->label_name;
						$view_name 			= $value->view_name;
						$unique_field 		= $value->unique_field;
						$excel_line_value 	= $value->excel_line_value;
						$multi_get_cell_value = $sheet->rangeToArray("$excel_line_value$excel_row_start:$excel_line_value$total_rows", NULL, TRUE, TRUE, TRUE);
						
						if((int)$unique_field === 1){
							$get_duplicat_value = $sheet->rangeToArray("$excel_line_value$excel_row_start:$excel_line_value$total_rows", NULL, TRUE, TRUE, TRUE);
							$get_duplicat_value = array_map('array_filter', $get_duplicat_value ?? []);//empty remove
							$get_duplicat_value = array_filter($get_duplicat_value ?? []);
							
							foreach ($get_duplicat_value as $current_key => $current_array) {
								$get_excel_val 	= $current_array[$excel_line_value];
								$exist_query = 'select count(*) uniq_exist_count from '.$this->prime_table.' where '.$label_name.' = "'.$get_excel_val.'" and trans_status =1';
								$exist_info   = $this->db->query("CALL sp_a_run ('SELECT','$exist_query')");
								$exist_result = $exist_info->result();
								$exist_info->next_result();
								foreach ($get_duplicat_value as $search_key => $search_array) {
									if($search_array["$excel_line_value"] == $current_array["$excel_line_value"]){
										if ($search_key != $current_key) {
											$err_column_array['error']["$excel_line_value$current_key"] = $view_name;
											$msg_line = "duplicate data present in column, please check it?";
											$err_column_tabview['error']["$excel_line_value$current_key"]  = $view_name." ".$msg_line;
										}
									}
									$exist_count = $exist_result[0]->uniq_exist_count;
									$array_uniq[$label_name]['view_name'] = $view_name;
									$array_uniq[$label_name]['label_name'] = $label_name;
								}

								if((int)$exist_count > 0){
									$err_column_array['error']["$excel_line_value$current_key"] = $view_name;
									$msg_line = "Data already exists for this Column";
									$err_column_tabview['error']["$excel_line_value$current_key"]  = $view_name." ".$msg_line;
								}
							}
						}
					}
					// get module unique column 
					$uniq_field_qry  = 'select view_name,label_name from  cw_form_setting where cw_form_setting.prime_module_id = "'.$module_id.'" and input_view_type IN(1,2) and field_show = 1 and unique_field = 1 and trans_status = 1';
					$uniq_field_info = $this->db->query("CALL sp_a_run ('SELECT','$uniq_field_qry')");
					$uniq_field_rslt = $uniq_field_info->result_array();
					$uniq_field_info->next_result();
					$uniq_field_rslt = array_reduce($uniq_field_rslt, function($result, $arr){	
						    $result[$arr['label_name']] = $arr;
						    return $result;
						}, array());
					$uniq_result 	 = array_diff_key($uniq_field_rslt,$array_uniq);
					if((int)$import_type === 1){
						foreach ($uniq_result as $uniq_key => $uniq_val) {
							$label_name 	= $uniq_val['label_name'];
							$err_column_array['error']["label_name"] = $uniq_val['view_name'];
							$msg_line = "Unique Field Column Missing";
							$err_column_tabview['error'][$uniq_val['view_name']]  = $uniq_val['view_name']." ".$msg_line;
						}
					}
					$err_column_count = count($err_column_array['error'] ?? []);
					$err_column       = implode(",",(array_unique($err_column_array['error'] ?? [])) ?? []);
					if((int)$err_column_count > 0){
						$table_info = $this->get_excel_error_ui($err_column_tabview);
						echo json_encode(array('success'=>false,'message'=>"Column Wise Error",'table_info'=>$table_info));
						exit();
					}
					
					$status_array	= array();
					for($row =$excel_row_start; $row <= $total_rows; $row++) {
						$prime_column_val = "";
						$prime_cell_val   = "";
						$exist_val        = "";
						$upd_qry_build    = ""; // [MS 12-08-2024]
						$status_info      = array();
						$status_info["Excel Row"] = $row;
						$sts              = TRUE;
						$mobile_sts       = TRUE;
						$email_sts        = TRUE;
						$picklist_sts     = TRUE;
						foreach($excel_format_result as $excel_info){
							$field_isdefault        = (int)$excel_info->field_isdefault;
							$mandatory_field        = (int)$excel_info->mandatory_field;
							$field_type             = (int)$excel_info->field_type;
							$pick_table             = $excel_info->pick_table;
							$pick_list_type         = (int)$excel_info->pick_list_type;
							$pick_list_import       = (int)$excel_info->pick_list_import;
							$pick_list              = $excel_info->pick_list;
							$excel_line_column_name = $excel_info->excel_line_column_name;
							$excel_line_value       = $excel_info->excel_line_value;
							$get_cell_value         = ucwords(trim($sheet->getCell("$excel_line_value$row")->getValue()));
                            if($get_cell_value){
								//FOR MOBILE NUMBER
								 if($field_type === 11){
									$length = strlen($get_cell_value);
									$length_query = 'select field_length from cw_form_setting where cw_form_setting.prime_module_id = "'.$module_id.'" and cw_form_setting.field_type = 11';
									$length_data  = $this->db->query("CALL sp_a_run ('SELECT','$length_query')");
									$length_result = $length_data->result();
									$length_data->next_result();
									$field_length = $length_result[0]->field_length;
									if($field_length != $length){
										$sts = FALSE;
									}else{
										// Validate mobile number
										if ((int)$this->validateMobileNumber($get_cell_value) === 0) {
    										$mobile_sts = FALSE;
										}else{
											$mobile_sts = TRUE;
										}		
									}
								}else 
								if($field_type === 12){
									//FOR EMAIL
									$email = $get_cell_value;
									if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
										$email_sts = FALSE;
									}
								}else
								if($field_type === 4){
									// FOR DATE
									$get_cell_value = trim(Date::excelToDateTimeObject((int)$sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));
								}else
								if($field_type === 13){
									$get_date_time 	= $sheet->getCell("$excel_line_value$row")->getValue();
									$date 			= DateTime::createFromFormat('d/m/Y H:i:s A', $get_date_time);
									$get_cell_value = $date->format('Y-m-d H:i:s');
								}else
								// FOR PICKLIST CHECK
								if(($field_type === 5) || ($field_type === 7)){
									if($pick_list_type === 1){
										$pick_list_val   = explode(",",$pick_list);
										$pick_list_val_1 = $pick_list_val[0];
										$pick_list_val_2 = $pick_list_val[1];
										$pick_query = 'select '.$pick_list.',trans_status from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
										if($pick_list_import === 1){
											$pick_query = 'select '.$pick_list.',trans_status from '.$pick_table.' where '.$pick_list_val_1.' = "'.$get_cell_value.'"';	
										}else{
											$pick_query = 'select '.$pick_list.',trans_status from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
										}	
										$pick_data  = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
										$pick_result = $pick_data->result();
										$pick_count  = $pick_data->num_rows();
										$pick_data->next_result();
										if((int)$pick_count === 0 && $mandatory_field === 0){
											if($pick_table !== $this->prime_table){
												$ins_query  = 'insert into '.$pick_table.'('.$pick_list_val_2.') VALUES ("'.$get_cell_value.'")';
												$ins_info   = $this->db->query("CALL sp_a_run ('INSERT','$ins_query')");
												$ins_result = $ins_info->result();
												$ins_info->next_result();
												$get_cell_value  = $ins_result[0]->ins_id;
											}
										}else
										if((int)$pick_count === 0 && $mandatory_field === 1){
											$status_info["$excel_line_value$row"] = "Invalid $get_cell_value";
											$message               = "Invalid $get_cell_value";
											$status                = FALSE;
											$picklist_sts          = FALSE;
										}else
										if((int)$pick_count === 1){
											if($pick_table !== $this->prime_table){
												$pick_id     = $pick_result[0]->$pick_list_val_1;
												$pick_status = (int)$pick_result[0]->trans_status;
												if($pick_status === 0 && $mandatory_field === 1){
													$status_info["$excel_line_value$row"] = "Invalid $get_cell_value";
													$message               = "Invalid $get_cell_value";
													$status                = FALSE;
													$picklist_sts          = FALSE;
												}else
												if($pick_status === 0 && $mandatory_field === 0){
													$upd_query  = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = '.$pick_id;
													$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
													$get_cell_value = $pick_id;
												}else
												if($pick_status === 1){
													$get_cell_value = $pick_id;
												}
											}
										}
									}else
									if($pick_list_type === 2){
										$pick_list_val_1 = $pick_table."_id";
										$pick_list_val_2 = $pick_table."_value";
										$pick_list_val_3 = $pick_table."_status";
										$pick_query = 'select * from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
										$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
										$pick_result = $pick_data->result();
										$pick_count  = $pick_data->num_rows();
										$pick_data->next_result();
										if((int)$pick_count === 0 && $mandatory_field === 0){
											$ins_query  = 'insert into '.$pick_table.'('.$pick_list_val_2.') VALUES ("'.$get_cell_value.'")';
											$ins_info   = $this->db->query("CALL sp_a_run ('INSERT','$ins_query')");
											$ins_result = $ins_info->result();
											$ins_info->next_result();
											$get_cell_value  = $ins_result[0]->ins_id;
										}else
										if((int)$pick_count === 0 && $mandatory_field === 1){
											$status_info["$excel_line_value$row"] = "Invalid $get_cell_value";
											$message               = "Invalid $get_cell_value";
											$status                = FALSE;
											$picklist_sts          = FALSE;
										}else
										if((int)$pick_count === 1){
											$pick_id     = $pick_result[0]->$pick_list_val_1;
											$pick_status = (int)$pick_result[0]->$pick_list_val_3;
											if($pick_status === 0 && $mandatory_field === 1){
												$status_info["$excel_line_value$row"] = "Invalid $get_cell_value";
												$message               = "Invalid $get_cell_value";
												$status                = FALSE;
												$picklist_sts          = FALSE;
											}else
											if($pick_status === 0 && $mandatory_field === 0){
												$upd_query  = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = '.$pick_id;
												$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
												$get_cell_value = $pick_id;
											}else
											if($pick_status === 1){
												$get_cell_value = $pick_id;
											}
										}
									}
								}
								if($field_isdefault === 1){
									$get_cell_value    = str_replace("'",'^', $get_cell_value);
									$prime_column_val .= $excel_line_column_name . ",";
									$prime_cell_val   .= "\'" . $get_cell_value . "\',";
									if(empty($exist_column_name)){
										 if($mandatory_field === 1){
											$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
										}
									}else{
										if(in_array($excel_line_column_name,$exist_column_name)){
											$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
										}
									}
								}
							}
							$upd_qry_build      .= ''.$excel_line_column_name.' = "'.$get_cell_value.'",'; // [MS 12-08-2024]
						}
						if($prime_column_val){
							$prime_id    = "prime_".$module_id."_id";
							$exist_val   = rtrim($exist_val," and ");
							$exist_query = "select count(*) exist_count,$this->prime_table.trans_status,$this->prime_table.$prime_id from $this->prime_table where $exist_val";
							$exist_info   = $this->db->query("CALL sp_a_run ('RUN','$exist_query')");
							$exist_result = $exist_info->result();
							$exist_info->next_result();
							$exist_count = $exist_result[0]->exist_count;
							$created_on  = date("Y-m-d h:i:s");
							if(!$sts){
								$status_info['status'] = "Mobile Number length should be 10";
							}
							else
							if(!$mobile_sts){
								$status_info['status'] = "Invalid Mobile Number";
							}
							else
							if(!$email_sts){
								$status_info['status'] = "Invalid Email";
							}else
							if((int)$exist_count === 0 && $picklist_sts){
								$prime_column_val .= "trans_created_by,trans_created_date";
								$prime_cell_val   .= '"'.$this->logged_id.'",'.'"'.$created_on.'"';
								$prime_column_val  = rtrim($prime_column_val,",");
								$prime_cell_val    = rtrim($prime_cell_val,",");
								$prime_query       = "insert into $this->prime_table ($prime_column_val) VALUES ($prime_cell_val)";
								$insert_info   = $this->db->query("CALL sp_a_run ('INSERT','$prime_query')");
								$insert_result = $insert_info->result();
								$insert_info->next_result();
								$insert_id = $insert_result[0]->ins_id;
								
								$status_info['Status'] = "Inserted to DB";
							}else
							if((int)$exist_count === 1 && $picklist_sts){
								$trans_status = (int)$exist_result[0]->trans_status;
								$upd_prime_id = (int)$exist_result[0]->$prime_id;
								$upd_query = 'UPDATE '.$this->prime_table.' SET '.$upd_qry_build.' trans_updated_by = "'.$this->logged_id.'",trans_updated_date = "'.$created_on.'" , trans_status = 1 WHERE '.$prime_id.' = "'.$upd_prime_id.'"'; // [MS 12-08-2024]
								$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
								$status_info['status'] = "Updated to DB";						
							}else
							if($picklist_sts){
								$status_info['status'] = "Already Exist in DB";
							}
							$status_array[] = $status_info;
						}
					}
					$table_info = $this->get_excel_import_ui($status_array);
					return json_encode(array('success'=>true,'message'=>"Successfully file imported",'table_info'=>$table_info));
				}
			}
		}
	}
	// MONTHLY INPUT IMPORT [MS 29-11-2024]
	//IMPORT DATA FROM FILE PATH
    public function do_monthly_excel_import($import_id,$allow_left){
        $this->save_info();
        if($import_id < 0){
            return json_encode(array('success' => false,'message' => "Invalid file upload"));
        }
        //EDIT START 
        $cat_qry         = 'select * from cw_category where trans_status = 1';
        $cat_data        = $this->db->query("CALL sp_a_run ('SELECT','$cat_qry')");
        $cat_data_result = $cat_data->result();
        $cat_data->next_result();
        $cat_data        = array_column($cat_data_result, 'category_name', 'prime_category_id');

        $excel_path_qry    = 'select * from cw_month_import where import_id = "' . $import_id . '"';
        $excel_path_info   = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
        $excel_path_result = $excel_path_info->result();
        $excel_path_info->next_result();
        if (!$excel_path_result){
            return json_encode(array('success' => false,'message' => "Invalid file upload"));
        }else{
            $excel_file_path  = $excel_path_result[0]->excel_file_path;
            $module_id        = $excel_path_result[0]->module_id;
            $excel_format     = $excel_path_result[0]->excel_format;
            $excel_sheet_name = (int) $excel_path_result[0]->excel_sheet_name;
            $excel_row_start  = (int) $excel_path_result[0]->excel_start_row;
            $excel_row_end    = (int) $excel_path_result[0]->excel_end_row;
            $process_month    = $excel_path_result[0]->process_month;
            $category_ids     = $excel_path_result[0]->category;
            $category_arr     = explode(",",$category_ids);
            		
            //Add Additional Column
            $add_input       		= "";
            $mi_process_type 		= "";
            $add_value       		= "";
            $upd_value       		= "";
			$fandf_value     		= "2";
			$fandf_employee_codes 	= [];
			
			// FILTER KEY AND ENTITY SET AUDIT LOG _ARN 07-10-2025
			$con_name               = ucwords(str_replace('_', ' ', $this->control_name));
			$filter_keys            = ["Process Month"=>$process_month,"Excel Format"=>$excel_format ,"Sheet Name"=> $excel_sheet_name];

            //FROM COMPANY INFORMATION
            if($this->company_info[0]->mi_process_type !== 'role' && $this->company_info[0]->mi_process_type !== '0'){
                $mi_process_type = $this->company_info[0]->mi_process_type;
                $add_input       = ','.$this->company_info[0]->mi_process_type;              
            }
			// FNAF MONTHLY INPUT CHECK TO PROCESS _ARN START 23-08-2025
			if($this->control_name === 'fandf_monthly_input'){
				$fandf_value    = "1";
				$date_search    = explode("-", $process_month);
        		$search_date    = $date_search[1] . "-" . $date_search[0] . "-01";
				$salary_days    = $this->Process_payroll_model->get_salary_date($category_ids);
				if($salary_days){
					$day_conditions = $salary_days['day_conditions'];
					if($day_conditions === 3){
						$sal_start_date = date("Y-m", strtotime("-1 month", strtotime($search_date)))."-".$salary_days['day_start'];
						$sal_end_date   = date("Y-m-" . $salary_days['day_end'], strtotime($search_date));                            
					}else{
						$sal_start_date  = date("Y-m-".$salary_days['day_start'], strtotime($search_date));
						$sal_end_date    = date("Y-m-".$salary_days['day_end'], strtotime($search_date));
						$sal_end_date    = date("Y-m-t", strtotime($search_date));
					}
					$bef_six_month    = date('Y-m-d', strtotime('-6 month', strtotime($sal_end_date)));
				}else{
					echo json_encode(array('success' => false,'status' => "Monthday",'message' => "Month days Not Set"));
					exit(0);
				}
				if($allow_left === 1){
					$status_qry = ' AND DATE_FORMAT(cw_employees.last_working_date, "%Y-%m-%d") <= "' . $sal_end_date . '" AND DATE_FORMAT(cw_employees.last_working_date, "%Y-%m-%d") >= "' . $bef_six_month . '" ';
				}else{
					$status_qry = ' AND DATE_FORMAT(cw_employees.last_working_date, "%Y-%m-%d") BETWEEN "' . $sal_start_date . '" AND "' . $sal_end_date . '" ';
				}
				$check_emp_code_qry = 'SELECT employee_code FROM cw_employees WHERE trans_status = 1 AND termination_status = 1 ' . $status_qry . ' AND role IN (' . $category_ids . ')';
                $check_emp_code_data  = $this->db->query("CALL sp_a_run('SELECT', '$check_emp_code_qry')");
                $check_employee_codes = $check_emp_code_data->result();
                $check_emp_code_data->next_result();	
				$fandf_employee_codes = [];
				foreach ($check_employee_codes as $row) {
					$fandf_employee_codes[] = $row->employee_code;
				}
			}
			//_ARN END OF PROCESS
			
			// PD DAYS GET TO PROCESS WAS GRAETER VALUES _ARN 
			$this->column_mapping();
			$get_map_column    = $this->get_map_arr['paid_days'];
			if(!$get_map_column){
				echo json_encode(array('success' => False, 'message' => "Column Not Mapped in Module settings. Please map and try aftersometime.."));
				exit(0);
			}
            //check payroll count //and role ="'.$category_id.'"
            $payroll_exist_qry    = 'select employee_code from cw_transactions where trans_status = 1 and transactions_month ="'.$process_month.'" and role in ('.$category_ids.')';
            $payroll_exist_info   = $this->db->query("CALL sp_a_run ('RUN','$payroll_exist_qry')");
            $payroll_exist_result = $payroll_exist_info->result_array();
            $payroll_exist_info->next_result();
            $pay_codes = array_column($payroll_exist_result,'employee_code');
           
			// LOP CREDIT CHCEK BERFORE CHNAGE MONTHLY INPUT AND FANDF EXISTS IN LOP CREDIT TRANS _ARN 23-09-2025
			$lop_credit_qry    = 'SELECT employee_code, SUM(credit_days) as credit_days_sum FROM cw_lop_credit_trans 
            WHERE trans_status = 1 AND process_month = "'.$process_month.'" GROUP BY employee_code';
			$lop_credit_data   = $this->db->query("CALL sp_a_run ('SELECT','$lop_credit_qry')");
			$lop_credit_result = $lop_credit_data->result();
			$lop_credit_data->next_result();

			$existing_lop_credit_employees = [];
			foreach($lop_credit_result as $row_data){
				$existing_lop_credit_employees[$row_data->employee_code] = (float)$row_data->credit_days_sum;
			}

            //EMPLOYEE CHECKS IN EMPLOYEE MASTER
            $emp_qry         = 'select prime_employees_id,employee_code,date_of_joining,role,emp_name,prime_employees_id,resignation_date,termination_status,payroll,grade,professional_tax_location '.$add_input.' from cw_employees where trans_status = 1 and role in ('.$category_ids.')';
            $emp_data        = $this->db->query("CALL sp_a_run ('SELECT','$emp_qry')");
            $emp_data_result = $emp_data->result();
            $emp_data->next_result();
            
            $emp_code_result = [];
			foreach($emp_data_result as $v){
				$return_array = [];
				$return_array['employee_data'] = $v;
				$return_array['employee_code'] = $v->employee_code;

				$emp_code_result[] = $return_array;
			}

            $emp_code_data    = array_column($emp_code_result, 'employee_data', 'employee_code');

            $lock_month_qry    = 'select * from cw_monthly_input_lock where lock_month = "'.$process_month.'" and status = 1 and trans_status = 1';
            $lock_month_data   = $this->db->query("CALL sp_a_run ('SELECT','$lock_month_qry')");
            $lock_month_result = $lock_month_data->result();
            $lock_month_data->next_result();
            $lock_num_rows = $lock_month_data->num_rows();
            if ((int) $lock_num_rows > 0) {
                return json_encode(array('success' => false,'message' => "Monthly input is locked this month, please unlocked to upload the files"));
                exit(0);
            }
            $format_qry  = 'select * from cw_util_excel_format where prime_excel_format_id = "' . $excel_format . '" and cw_util_excel_format.trans_status = 1';
            $format_info = $this->db->query("CALL sp_a_run ('SELECT','$format_qry')");
            $format_rslt = $format_info->result();
            $format_info->next_result();

			//UPDATE MONTHLY INPUT TABLE CURRENT MONTH RESIGNED EMPLOYEES _ARN 09-12-2025
            $re_and_act_emp_upd  = 'UPDATE cw_monthly_input JOIN cw_employees ON cw_monthly_input.employee_code = cw_employees.employee_code SET cw_monthly_input.termination_status = cw_employees.termination_status,cw_monthly_input.role = cw_employees.role,cw_monthly_input.payroll = cw_employees.payroll WHERE cw_monthly_input.input_status = 0 and cw_monthly_input.process_month = "'.$process_month.'"';
            // SESSION SET AUDIT LOG _ARN 10-10-2025
			$this->session_setter($filter_keys,"Mothly Input Termination and Active Status DATA UPDATE",'');
            $this->db->query($re_and_act_emp_upd);
			
            if(!$format_rslt){
                return json_encode(array('success' => false,'message' => "Please add excel format before import"));
            }else{
                $exist_column_name   = explode(",", $format_rslt[0]->exist_column_name);
                $excel_format_qry    = 'select * from cw_util_excel_format_line inner join cw_form_setting on label_name = excel_line_column_name where excel_line_module_id = "' . $module_id . '" and prime_excel_format_id = "' . $excel_format . '" and cw_util_excel_format_line.trans_status = 1 group by excel_line_column_name';
                $excel_format        = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
                $excel_format_result = $excel_format->result();
                $excel_format->next_result();
                $excel_columns       = array_column($excel_format_result, 'excel_line_column_name');          

                $lock_query  = 'select GROUP_CONCAT(previous_column) as previous_column from cw_monthly_input_previous inner join cw_form_setting on cw_form_setting.label_name = previous_column where cw_monthly_input_previous.trans_status = 1 and column_status in (1,2)';
                $lock_data   = $this->db->query("CALL sp_a_run ('SELECT','$lock_query')");
                $lock_result = $lock_data->result();
                $lock_data->next_result();
                $previous_columns = explode(",",$lock_result[0]->previous_column);
                $result_arr       = array_intersect($excel_columns,$previous_columns);
                $error_string     = implode(",", $result_arr ?? []);

                //------------ CATEGORY BASED MONTH DAY SETTING CHECKING --------------------------------
                //GET EMPLOYEE MASTER EARNINGS AND DEDUCTIONS COLUMN(LABELS) ARRAY
                $ear_ded_col_qry  = 'SELECT label_name,view_name FROM `cw_form_setting` WHERE cw_form_setting.prime_module_id = "employees" and cw_form_setting.input_for in ("34","49") and cw_form_setting.trans_status = 1';		
                $ear_ded_col_info = $this->db->query("CALL sp_a_run ('SELECT','$ear_ded_col_qry')");
                $ear_ded_col_rslt = $ear_ded_col_info->result_array();
                $ear_ded_col_info->next_result();

                $ear_ded_col_arr  = array_column($ear_ded_col_rslt,'label_name','label_name'); 
              
                //GET CATEGORY BASED MONTH DAY SETTINGS ARRAY
                $mon_day_set_qry  = 'select prime_month_day_id,category from cw_month_day where cw_month_day.trans_status = 1';
                $mon_day_set_data = $this->db->query("CALL sp_a_run ('SELECT','$mon_day_set_qry')");
                $mon_day_set_rslt = $mon_day_set_data->result_array();
                $mon_day_set_data->next_result();
				// COMMENTED BY _ARN FOR REASON THIS FUNCTION NOT DEFINED
                $mon_day_err_data = $this->cat_settings_err($mon_day_set_rslt,$category_arr,$cat_data);
                if($mon_day_err_data){
                    return json_encode(array('success' => FALSE,'message' => " Please Map Month Day Settings for the Category of $mon_day_err_data"));
                    exit(0);
                }
               
                //------------ CATEGORY BASED STATUTORY SETTING CHECKING --------------------------------
                $stat_err_col_arr   = $this->statutory_setting_validate($ear_ded_col_arr,$category_arr,$cat_data);
                if(!empty($stat_err_col_arr)){
                    return json_encode($stat_err_col_arr);
                    exit(0);
                }
                //------------ CATEGORY BASED GRATUITY SETTING CHECKING --------------------------------
                $grat_err_col_arr   = $this->gratuity_setting_validate($ear_ded_col_arr,$category_arr,$cat_data);
                if(!empty($grat_err_col_arr)){
                    return json_encode($grat_err_col_arr);
                    exit(0);
                }
    
                //---------- PROFESSIONAL TAX VALIDATION START --------------------
                // PROFESSIONAL TAX LOCATION NAME GET FROM THE TAX LOCATION MASTER
                $pro_loc_qry      = 'select cw_professional_tax_location.prime_professional_tax_location_id as location_id,cw_professional_tax_location.professional_tax_location from cw_professional_tax_location where cw_professional_tax_location.trans_status = 1';
                $pro_loc_data     = $this->db->query("CALL sp_a_run ('SELECT','$pro_loc_qry')");
                $pro_loc_rslt     = $pro_loc_data->result_array();
                $pro_loc_data->next_result();
                $loc_name_arr      = array_column($pro_loc_rslt,'professional_tax_location','location_id');
                
                //PROFESSIONAL TAX AND TAX RANGE TABLE JOIN TO GET A TAX LOCATION ID 
                $pro_tax_qry      = 'select cw_professional_tax.prime_professional_tax_id,cw_professional_tax.location from cw_professional_tax inner join cw_professional_tax_tax_range on cw_professional_tax_tax_range.prime_professional_tax_id = cw_professional_tax.prime_professional_tax_id where cw_professional_tax.trans_status = 1 and cw_professional_tax_tax_range.trans_status = 1 GROUP BY prime_professional_tax_id';
                $pro_tax_data     = $this->db->query("CALL sp_a_run ('SELECT','$pro_tax_qry')");
                $pro_tax_rslt     = $pro_tax_data->result_array();
                $pro_tax_data->next_result();
                $pro_tax_arr      = array_column($pro_tax_rslt,'location','prime_professional_tax_id');
                //---------- PROFESSIONAL TAX VALIDATION END --------------------

                if(!empty($result_arr)){
                    return json_encode(array('success' => FALSE,'message' => " Columns $error_string are not Allowed to import.. These are Carry Forward Inputs.."));
                    exit(0);
                }

                if(!$excel_format_result){
                    return json_encode(array('success' => FALSE,'message' => "Please map excel cell column before import"));
                }else{
                    try {
                        $excel_obj = \PhpOffice\PhpSpreadsheet\IOFactory::load($excel_file_path);
                    }
                    catch(Exception $e){
                        die('Error loading file "' . pathinfo($excel_file_path, PATHINFO_BASENAME) . '": ' . $e->getMessage());
                        return json_encode(array(
                            'success' => false,
                            'message' => "Invalid file or path"
                        ));
                    }
                    $sheet = $excel_obj->getSheet($excel_sheet_name);
                    if($excel_row_end){
                        $total_rows = $excel_row_end;
                    } else {
                        $total_rows = $sheet->getHighestRow();
                    }
                    $highest_column = $sheet->getHighestColumn();
                    $error_info     = array();
					$insert_val     = '';
                    for($row = $excel_row_start; $row <= $total_rows; $row++){
                        $exist_val                = "";
                        $prime_column_val         = "";
                        $prime_cell_val           = "";
                        $status_info              = array();
                        $status_info["Excel Row"] = $row;
                        $prime_upd_query          = "";
						$paid_days                = "";
                        foreach ($excel_format_result as $excel_info) {
                            $column_name    = $excel_info->excel_line_column_name;
                            $column_value   = $excel_info->excel_line_value;
                            $field_type     = (int) $excel_info->field_type;
                            $get_cell_value = trim($sheet->getCell("$column_value$row")->getCalculatedValue());
                            if($column_name === "employee_code"){
                                $employee_code    = $get_cell_value;
                                //Get Salary Start and End Date;
                                $emp_data             	= $emp_code_data[$get_cell_value];
                                $emp_doj          		= $emp_data->date_of_joining;
                                $category         		= $emp_data->role;
                                $emp_status       		= (int)$emp_data->termination_status;
                                $pro_tax_loc      		= (int)$emp_data->professional_tax_location;

								// CATEGORY HAVE VALUE THAT TIME ONLY CHCEK _ARN 25-08-2025
								if($category){
									$salary_dates = $this->Process_payroll_model->get_salary_date($category);
								}
                                $day_start        = $salary_dates['day_start'];
                                $day_end          = $salary_dates['day_end'];
                                $process_date     = date("Y-m-d", strtotime($day_end . "-" . $process_month));
                                $sal_start_date   = date("Y-m-d", strtotime($day_start . "-" . $process_month));
								
								// INACTIVE EMPLOYEE CODE CHCEKING _ARN 25-08-2025
								if($this->control_name === 'fandf_monthly_input'){
									if(!in_array($employee_code, $fandf_employee_codes)){
										$error_info[$row] = "Employee Code Is Active or not leave this month ";
									}
								}
                                //VALIDATIONS CHECKING
                                if(!array_key_exists($get_cell_value, $emp_code_data)){
                                    $error_info[$row] = "Employee Code Not Exist in DB";
                                }else
                                 if(strtotime($emp_doj) > strtotime($process_date)){
                                    $error_info[$row] = "Date of Joining Greater than Process date.!";
                                }else
                                if(in_array($employee_code, $pay_codes)){
                                    $error_info[$row] = "Payroll Already Exist for this Employee.!";
                                }else 
								// LOP CREDIT CHCEK BEFORE UPDATE THE DATA _ARN 23-09-2025
								if(isset($existing_lop_credit_employees[$employee_code]) && $existing_lop_credit_employees[$employee_code] > 0){
									$error_info[$row] = "Lop Credit Already Processed.. Please remove and try again";
								}else
								// TERMINATION CHCEK NOT IN FANDF  _ARN 25-08-2025
                                if($emp_status === 1 && $this->control_name !== 'fandf_monthly_input'){
                                    $error_info[$row] = "Resigned Employee.!";
                                }else
                                if($pro_tax_loc){
                                    if(!in_array($pro_tax_loc,$pro_tax_arr)){
                                        $tax_loc_name     =  $loc_name_arr[$pro_tax_loc];
                                        $error_info[$row] = "In Employee Code $employee_code,Please Should Map Tax Range for $tax_loc_name Location.!";
                                    }
                                }
                            }
							if($column_name === $get_map_column){
								$paid_days    = $get_cell_value;
							}
                        }
						$paid_day_count   = $this->get_total_work_days($category,$process_month);
						if($paid_days > $paid_day_count){
							$error_info[$row] = "Paid Days Must Be Equal To Or Lesser Than Month Days";
						}
                    }
                    $can_process_count = count($error_info);
                    if((int) $can_process_count > 0){
                        return json_encode(array('success' => true, 'message' => "File Has Error",'error_info' => $error_info));
                    }else{
                        $status_array = array();
                        for($row = $excel_row_start; $row <= $total_rows; $row++){
                            $exist_val                = "";
                            $prime_column_val         = "";
                            $prime_cell_val           = "";
                            $status_info              = array();
                            $status_info["Excel Row"] = $row;
                            $prime_upd_query          = "";
                            foreach($excel_format_result as $excel_info){
                                $column_name    = $excel_info->excel_line_column_name;
                                $column_value   = $excel_info->excel_line_value;
                                $get_cell_value = trim($sheet->getCell("$column_value$row")->getCalculatedValue());
                            
                                if($column_name === "employee_code"){
                                    $employee_code = $get_cell_value;
                                    $emp_data      = $emp_code_data[$get_cell_value];
                                    $doj           = $emp_data->date_of_joining;
                                    $emp_id        = $emp_data->prime_employees_id;
                                    $cat_id        = $emp_data->role;
                                    $emp_name      = $emp_data->emp_name;
									$emp_status    = (int)$emp_data->termination_status;
                                    $emp_cell_val  = $emp_id;
                                    if($mi_process_type){
                                        $add_value = ",".$emp_data->$mi_process_type;
                                        $upd_value = $add_input.' = "'.$emp_data->$mi_process_type.'"';
                                    } 
                                }
								
                                //INSERT AND UPDATE QUERY DATA
                                $prime_column_val .= $column_name . ",";
                                $prime_cell_val   .= '"' . $get_cell_value . '",';
								
                                
                                $update_column_val = $column_name;
                                $update_cell_val   = '"' . $get_cell_value . '",';
                                $prime_upd_query  .= $update_column_val . "=" . $update_cell_val;
                                //EXIST QUERY DATA
                                if(in_array($column_name, $exist_column_name)){
                                    $exist_val    .= $column_name . ' = "' . $get_cell_value . '" and ';
                                }
                            }

							// MONTHLY INPUT & FANDF INSERT QRY BUILD  TERMINATION STS _ARN 25-08-2025
							$prime_column_val .= 'termination_status ,';
							$prime_cell_val   .= '"' . $emp_status . '",' ;
							

                            $exist_val    = rtrim($exist_val, " and ");
                            $exist_query  = 'select count(*) exist_count,trans_status,prime_monthly_input_id from cw_monthly_input where trans_status = 1 and ' . $exist_val . ' and process_month ="' . $process_month . '"';
                            $exist_info   = $this->db->query("CALL sp_a_run ('RUN','$exist_query')");
                            $exist_result = $exist_info->result();
                            $exist_info->next_result();
                            $exist_count  = $exist_result[0]->exist_count;
                            $created_on   = date("Y-m-d h:i:s");
                            //INSERT PROCESS
                            if((int)$exist_count === 0){
                                $prime_column_val .= "employees_id,emp_name,role,date_of_joining,process_month,trans_created_by,trans_created_date,fandf,input_status $add_input";
                                $prime_cell_val .= '"'.$emp_cell_val.'","'.$emp_name.'","'.$cat_id.'","'.$doj.'","'. $process_month.'","'.$this->logged_id.'",'.'"'.$created_on.'","'. $fandf_value.'","1"'.$add_value;
                                $prime_column_val      = rtrim($prime_column_val, ",");
                                $prime_cell_val        = rtrim($prime_cell_val, ",");
                                $prime_query           = "insert into cw_monthly_input ($prime_column_val) VALUES ($prime_cell_val)";
								// SESSION SET AUDIT LOG _ARN 10-10-2025	
								$this->session_setter($filter_keys,$con_name ."DATA ADD",'user');
                                $insert_info           = $this->db->query($prime_query);
                                $status_info['Status'] = "Inserted to DB";
                            }else //UPDATE PROCESS
                            if((int) $exist_count > 0){
                                $trans_status = (int)$exist_result[0]->trans_status;
                                $upd_prime_id = (int)$exist_result[0]->prime_monthly_input_id;
                                $prime_upd_query .= 'trans_updated_by = "' . $this->logged_id . '",trans_updated_date = "' . $created_on . '",fandf="' . $fandf_value . '"';
                                if($trans_status === 1){ //and role = "'.$cat_id.'"
                                    $upd_query = 'UPDATE cw_monthly_input SET ' . $prime_upd_query . ',input_status = 1 '.$upd_value.' WHERE prime_monthly_input_id = "' . $upd_prime_id . '"';      
									// SESSION SET AUDIT LOG _ARN 10-10-2025	
									$this->session_setter($filter_keys,$con_name ."DATA UPDATE",'user');                              
									$this->db->query($upd_query);
                                    $status_info['status'] = "Updated to DB";
                                }else{
                                    $status_info['status'] = "Already Exist in DB";
                                }
                            }
                            $status_array[] = $status_info;
                        }
                    }
                }
                $table_info = $this->get_excel_import_ui($status_array);
                return json_encode(array('success' => true,'message' => "Successfully file imported",'table_info' => $table_info));
            }
        }
    }    
	// ================= DIRECT HR IMPORT ONDUTY - BUISNESS ON DUTY =================
	public function do_excel_direct_hr_import($import_id){
		if ($import_id < 0) {
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}
		$excel_path_qry = 'select * from cw_import where import_id = "' . $import_id . '"';
		$excel_path_info = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
		$excel_path_result = $excel_path_info->result();
		$excel_path_info->next_result();	
		if (!$excel_path_result) {
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
			exit(0);
		}else{
			$excel_file_path  = $excel_path_result[0]->excel_file_path;
			$excel_sheet_name = (int) $excel_path_result[0]->excel_sheet_name;
			$excel_row_start  = (int) $excel_path_result[0]->excel_start_row;
			$excel_row_end    = (int) $excel_path_result[0]->excel_end_row;	
			$excel_format	  = (int) $excel_path_result[0]->excel_format;	
			$today_date		  =  date("Y-m-d");
			try{
				$excel_obj = \PhpOffice\PhpSpreadsheet\IOFactory::load($excel_file_path);
			}catch (Exception $e){
				die('Error loading file "' . pathinfo($excel_file_path, PATHINFO_BASENAME) . '": ' . $e->getMessage());
				return json_encode(array('success' => false, 'message' => "Invalid file or path"));
			}	
			$sheet = $excel_obj->getSheet($excel_sheet_name);
			if($excel_row_end){
				$total_rows = $excel_row_end;
			}else{
				$total_rows = $sheet->getHighestRow();
			}
			$leave_financial_info = $this->get_leave_financial_details();
			$financial_year_id    = $leave_financial_info[0]->prime_leave_financial_year_id;
			$starting_date        = $leave_financial_info[0]->starting_date;
			$ending_date          = $leave_financial_info[0]->ending_date;
			
			$component_query  = 'SELECT pick_table,pick_list,components,label_name,view_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 = 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();			
			$component        = $component_result[0]->label_name;
			$view_name        = $component_result[0]->view_name;

			$employee_query   = 'select employee_code,termination_status,resignation_date,date_of_joining,'.$component.' as component_value from cw_employees where trans_status = 1 and termination_status = 0';
			$employee_info    = $this->db->query("CALL sp_a_run ('SELECT','$employee_query')");
			$employee_rslt 	  = $employee_info->result_array();
			$employee_info->next_result();			
			
			$employee_rslt_arr = array();
			foreach($employee_rslt as $emp_key => $emp_val){
				$employee_rslt_arr[$emp_val['employee_code']] = $emp_val;
			}
			//Weekoff array
			$check_weekoff_qry    = 'SELECT employee_code,weekoff_date,weekoff_type FROM cw_weekoff_import WHERE financial_setting_id = '.$financial_year_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_arr          = array();
			foreach($check_weekoff_rlst as $key => $val){
				$weekoff_arr[$val['employee_code']][$val['weekoff_date']] = $val['weekoff_type'];
			}
			//Holiday array
			$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_label_name       = $holid_component_result[0]->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_data.holiday_date between "'.$starting_date.'" and "'.$ending_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_array();
			$holiday_info->next_result();
			$holiday_result      = array_reduce($holiday_result, function($result, $arr){	
				$result[$arr['holiday_date']] = $arr;
				return $result;
			}, array());	
			
			$existing_qry = 'SELECT employee_code, from_date, to_date FROM cw_direct_leave_entry WHERE financial_setting_id = "'.$financial_year_id.'" 
			AND trans_status = 1';
			$existing_info = $this->db->query("CALL sp_a_run ('SELECT','$existing_qry')");
			$existing_result = $existing_info->result_array();
			$existing_info->next_result();

			$existing_arr = [];
			foreach($existing_result as $row){
				$emp   = $row['employee_code'];
				$from  = $row['from_date'];
				$to    = $row['to_date'];
				$existing_arr[$emp][$from][$to] = 1;
			}

			$validate_arr        = $this->build_common_valid_array();	
			//TIME OF SETTING BASED SALARY START AND END DATE DETAILS
			$last_payroll_month  = 'select max(date_format(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y") , "%Y-%m")) as max_month from cw_transactions where trans_status = 1';
			$last_payroll_info   = $this->db->query("CALL sp_a_run ('SELECT','$last_payroll_month')");
			$last_payroll_rslt   = $last_payroll_info->result();
			$last_payroll_info->next_result();
			$last_pay_month      = $last_payroll_rslt[0]->max_month;
			
			// $nxt_month           = date("d-m-Y", strtotime($last_pay_month."-01"));
			if(!empty($last_pay_month)){
				$nxt_month = date("d-m-Y", strtotime($last_pay_month . "-01"));
			}else{
				$nxt_month = ''; // or set default like '01-01-1900'
			}
			//GET SALARY FROM DATE
			$month_day_result    = $this->tos_day_qry_fun("3");
			$day_start           = $month_day_result[0]->day_start;
			$salary_start_date   = date("Y-m",strtotime($nxt_month))."-".$day_start;

			$get_date_type_qry   = 'SELECT * FROM cw_day_type where trans_status = 1';
			$get_date_type_info  = $this->db->query("CALL sp_a_run ('SELECT','$get_date_type_qry')");
			$get_date_type_rslt  = $get_date_type_info->result_array();
			$get_date_type_info->next_result();
			$columnValues        = array_column($get_date_type_rslt, 'prime_day_type_id', 'day_type');
			
			$err_column_tabview  = array();
			$excel_dupl_arr      = array();
			$insert_qry_val      = "";
			for($row = $excel_row_start; $row <= $total_rows; $row++){
				$insert_arr = [];
				$status     = 1;
				// ----------- A ROW EMPLOYEE CODE VALIDATIOSN ----------------
				$employee_code   = ucwords(trim($sheet->getCell("A$row")->getValue()));
				if($employee_code){ // Employee Code
					$date_of_joining = $employee_rslt_arr[$employee_code]['date_of_joining'];
					$component_value =  $employee_rslt_arr[$employee_code]['component_value'];
					if(!$employee_code){
						$err_column_tabview['error']["A$row"]  = "Employee Code is Empty,Please check..";
						$status = 0;
					}else
					if(!$employee_rslt_arr[$employee_code]){					
						$err_column_tabview['error']["A$row"]  = "Employee Code Not Exist or Inactive..";
						$status = 0;
					}else
					if(!$component_value){
						$err_column_tabview['error']["A$row"]  = "$view_name Not Mapped in Employee Master Please Check..!";
						$status = 0;
					}
				}
				//--------------- B-ROW FROM DATE VALIDATIONS -----------------------					
				$cell      = $sheet->getCell("B$row");
				$value     = $cell->getValue();
				$from_date = "";
				// Handle Excel date formats correctly
				if(is_numeric($value)){
					// Excel numeric date
					$from_date = date('Y-m-d', \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($value));
				}else{
					// Text date
					$from_date = trim($cell->getFormattedValue());
					$from_date = date('Y-m-d', strtotime($from_date));
				}
				// Validate empty / invalid date
				if(empty($from_date) || $from_date == "1970-01-01" || $from_date == "0000-00-00"){
					$err_column_tabview['error']["B$row"] = "Invalid From Date, please use DD-MM-YYYY format";
					$status = 0;
				}
				// Custom date validation
				if((int)$this->validateDATE(date('d-m-Y', strtotime($from_date))) === 0){
					$err_column_tabview['error']["B$row"] = "Invalid Date, please set correct format (DD-MM-YYYY)";
					$status = 0;
				}
				$from_date 	= Date('Y-m-d',strtotime($from_date));	

				// ------------------- C-ROW FROM DATE TYPE Validations ------------------------
				$from_date_type = trim($sheet->getCell("C$row")->getValue());
				if($from_date_type !== "FULL DAY" && $from_date_type !== "1ST HALF" && $from_date_type !== "2ND HALF"){
					$err_column_tabview['error']["C$row"]  = "Please Give Correct Format type (FULL DAY/1ST HALF/2ND HALF)";
					$status = 0;
				}		
				if($validate_arr[$employee_code][$from_date][$columnValues[$from_date_type]]){
					$err_column_tabview['error']["C$row"]  = " Request Already exist..";
					$status = 0;
				}else
				if($excel_dupl_arr[$employee_code][$from_date][$from_date_type]){
					$err_column_tabview['error']["C$row"]  = " Same Data Already Exist in Excel..";
					$status = 0;
				}else
				if($excel_dupl_arr[$employee_code][$from_date]["FULL DAY"]){
					$err_column_tabview['error']["C$row"]  = "Already Exist in Excel,Please Check..!";
					$status = 0;
				}
			
				//---------------------- D-ROW TO DATE VALIDATIONS----------------------
				$cell     = $sheet->getCell("D$row");
				$value    = $cell->getValue();
				$to_date  = "";
				// Handle Excel date formats
				if(is_numeric($value)){
					// Excel numeric date
					$to_date = date('Y-m-d', \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($value));
				}else{
					// Text date
					$to_date = trim($cell->getFormattedValue());
					$to_date = date('Y-m-d', strtotime($to_date));
				}
				// Validate empty / invalid
				if(empty($to_date) || $to_date == "1970-01-01" || $to_date == "0000-00-00"){
					$err_column_tabview['error']["D$row"] = "Invalid To Date, please use DD-MM-YYYY format";
					$status = 0;
				}

				// Custom validation (your existing function)
				if((int)$this->validateDATE(date('d-m-Y', strtotime($to_date))) === 0){
					$err_column_tabview['error']["D$row"] = "Invalid Date, please set correct format (DD-MM-YYYY)";
					$status = 0;
				}
				$to_date	= Date('Y-m-d',strtotime($to_date));

				//----------------------  E - ROW TO DATE TYPE VALIDATIONS -------------------
				$to_date_type    =  ucwords(strtoupper(trim($sheet->getCell("E$row")->getValue())));
				if($to_date_type !== "FULL DAY" && $to_date_type !== "1ST HALF" && $to_date_type !== "2ND HALF"){
					$err_column_tabview['error']["C$row"]  = "Please Give Correct Format type (FULL DAY/1ST HALF/2ND HALF)";
					$status = 0;
				}else
				if($from_date === $to_date && $from_date_type !== $to_date_type){
					$err_column_tabview['error']["$row"]  = "Please Check Your Data..";
					$status = 0;
				}else
				if($from_date < $to_date && ($from_date_type === '1ST HALF' || $to_date_type === '2ND HALF')){
					$err_column_tabview['error']["$row"]  = "Please Check Your Data..";
					$status = 0;
				}

				# From date validation -> NB[13-12-2023]
				if($validate_arr[$employee_code][$from_date][1]){
					if($from_date_type === "1ST HALF" || $from_date_type === "2ND HALF"){
						$err_column_tabview['error']["C$row"] = "Invalid - Full Day Request Already Submitted[$from_date].";
						$status = 0;
					}else if($from_date_type === "FULL DAY"){
						$err_column_tabview['error']["C$row"]  = "Invalid - Duplicate Entry, Data Already exist[$from_date].";
						$status = 0;
					}
				}else
				if(!empty($validate_arr[$employee_code][$from_date][2]) || !empty($validate_arr[$employee_code][$from_date][3])){
					if($from_date_type === "FULL DAY"){
						$err_column_tabview['error']["C$row"]  = "Invalid - 1ST HALF/2ND HALF Request Already Submitted[$from_date]";
						$status = 0;
					}else if($validate_arr[$employee_code][$from_date][2] && $from_date_type === "1ST HALF" || $validate_arr[$employee_code][$from_date][3] && $from_date_type === "2ND HALF"){
						$err_column_tabview['error']["C$row"]  = "Invalid - Duplicate Entry, Data Already exist[$from_date].";
						$status = 0;
					}
				}

				# To date validation.
				if($validate_arr[$employee_code][$to_date][1]){
					if($to_date_type === "1ST HALF" || $to_date_type === "2ND HALF"){
						$err_column_tabview['error']["E$row"]  = "Invalid - Full Day Request Already Submitted[$to_date].";
						$status = 0;
					}else if($to_date_type === "FULL DAY"){
						$err_column_tabview['error']["E$row"]  = "Invalid - Duplicate Entry, Data Already exist[$to_date].";
						$status = 0;
					}
				}else
				if(!empty($validate_arr[$employee_code][$to_date][2]) || !empty($validate_arr[$employee_code][$to_date][3])){
					if($to_date_type === "FULL DAY"){
						$err_column_tabview['error']["E$row"]  = "Invalid - 1ST HALF/2ND HALF Request Already Submitted[$to_date].";
						$status = 0;
					}else if($validate_arr[$employee_code][$to_date][2] && $to_date_type === "1ST HALF" || $validate_arr[$employee_code][$to_date][3] && $to_date_type === "2ND HALF"){
						$err_column_tabview['error']["E$row"]  = "Invalid - Duplicate Entry, Data Already exist[$to_date].";
						$status = 0;
					}
				}

				$day_data   = $validate_arr[$employee_code][$to_date] ?? [];
				if(!empty($validate_arr[$employee_code][$to_date][$columnValues[$to_date_type]])){
					$err_column_tabview['error']["B$row"]  = " Request Already exist..";
					$status = 0;
				}else
				if(!empty($day_data[1])){
					$err_column_tabview['error']["C$row"]  = " Full Day Request Already exist..";
					$status = 0;
				}else 
				if(!empty($day_data[2]) && !empty($day_data[3])){
					$err_column_tabview['error']["C$row"]  = " 2 Request Already Exist for different Date Type..";
					$status = 0;
				}
				if($excel_dupl_arr[$employee_code][$to_date][$to_date_type]){
					$err_column_tabview['error']["E$row"]  = " Same Data Already Exist in Excel..";
					$status = 0;
				}else
				if($excel_dupl_arr[$employee_code][$to_date]["FULL DAY"]){
					$err_column_tabview['error']["E$row"]  = "Already Exist in Excel,Please Check..!";
					$status = 0;
				}
					
				// -------------------- F ROW VA GETTING AND VALIDATIONS ---------------------
				$vacation_address = "";
				if($excel_format === 8){ //Business Trip
					$vacation_address   = ucwords(trim($sheet->getCell("F$row")->getValue()));
				}
					
				if($from_date > $to_date){
					$err_column_tabview['error']["D$row"]  = "To date lesser than From Date, please Check..!";
					$status = 0;
				}
				if($last_pay_month){
					if($from_date < $salary_start_date){
						$err_column_tabview['error']["D$row"]  = "Payroll Already Processed In this date..!";
						$status = 0;
					}
				}
			
				if($date_of_joining > $from_date){
					$err_column_tabview['error']["B$row"]  = " Date Of Joining Greater than From Date..!";
					$status = 0;
				}
				$weekoff_result = array();
				if(isset($weekoff_arr[$employee_code])){
					foreach($weekoff_arr[$employee_code] as $date => $type){
						if($date >= $from_date && $date <= $to_date){
							$weekoff_result[$employee_code][$date] = $type;
						}
					}
				}

				$created_on  = date("Y-m-d H:i:s");
				if(($from_date && $to_date) && $from_date < $to_date){
					if((int)$this->validateDATE($from_date) === 0  && (int)$this->validateDATE($to_date) === 0){
						$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);
						$insert_arr[$from_date] = $columnValues[$from_date_type];
						foreach ($date_range as $date){
							$chk_date = $date->format('Y-m-d');
							if(!$weekoff_result[$employee_code][$chk_date] && !$holiday_result[$chk_date]){
								if ($chk_date !== $str_date && $chk_date !== $finish_date) {
									$excel_dupl_arr[$employee_code][$chk_date]["FULL DAY"] = 1;
									$excel_dupl_arr[$employee_code][$chk_date]["1ST HALF"] = 0.5;
									$excel_dupl_arr[$employee_code][$chk_date]["2ND HALF"] = 0.5;
									$date_count_val = $validate_arr[$employee_code][$chk_date];
									if($date_count_val){
										$err_column_tabview['error']["E$row"]  = "Leave Or Onduty Already Exist in ($chk_date)in this given date..!";
										$status = 0;
									}else{
										$insert_arr[$chk_date] = 1; 
									}
								}
							}							
						}
					}
				}	

				$excel_dupl_arr[$employee_code][$to_date][$to_date_type] = 0.5;
				$from_date_type_check                                    = $columnValues[$from_date_type];
				$to_date_type_check	                                     = $columnValues[$to_date_type];
				if((int)$status === 1){ 
					if($from_date <= $to_date){
						$insert_arr[$to_date] = $columnValues[$to_date_type]; 		
					}							
				}else{
					$insert_arr               = array();
				}

				if(isset($existing_arr[$employee_code][$from_date][$to_date])){
					$err_column_tabview['error']["$row"] = "Already exists in DB..!";
					$status = 0;
				}

				if((int)$status === 1){
					$direct_leave_qry = 'insert into cw_direct_leave_entry (employee_code,component_value,date_of_joining,request_date,request_type,from_date,from_date_type,to_date,to_date_type,financial_setting_id,vacation_address,trans_created_by,trans_created_date) values ("'.$employee_code.'","'.$component_value.'","'.$date_of_joining.'","'.$today_date.'","'.$excel_format.'","'.$from_date.'","'.$from_date_type_check.'","'.$to_date.'","'.$to_date_type_check.'","'.$financial_year_id.'","'.$vacation_address.'","'.$this->logged_id.'","'.$created_on.'")';
					$direct_leave_info   = $this->db->query("CALL sp_a_run ('INSERT','$direct_leave_qry')");
					$direct_leave_result = $direct_leave_info->result();
					$direct_leave_info->next_result();
					$direct_leave_id     = $direct_leave_result[0]->ins_id;
					
					$insert_qry_val = "";
					foreach($insert_arr as $date => $day_type){
						$count      = 0.5;
						if((int)$day_type === 1){
							$count  = 1;
						}
						$insert_qry_val  .= '("'.$employee_code.'","'.$component_value.'","'.$date.'","'.$day_type.'","2","'.$count.'","'.$financial_year_id.'","'.$direct_leave_id.'","'.$this->logged_id.'","'.$created_on.'"),';
						
					}
					if($insert_qry_val && $direct_leave_id){
						$insert_qry_val    = rtrim($insert_qry_val,',');
						$final_insert_qry  ='insert into cw_on_duty_entry(employee_code,component_value,on_duty_date,date_type,on_duty_status,on_duty_count,financial_setting_id,prime_direct_entry_id,trans_created_by,trans_created_date) values '.$insert_qry_val.'';
						$insert_info       = $this->db->query("CALL sp_a_run ('INSERT','$final_insert_qry')");
						$insert_info->result();
						$insert_info->next_result();
						$err_column_tabview["success"]["$row"]  = "inserted to DB..!";
					}	
				}				
			}	
			if(count($err_column_tabview ?? []) > 0){
				$msg     = "Process Completed.. Please check the status below..!";
				$table_info = $this->get_excel_error_ui($err_column_tabview);				
			}

		}
		echo json_encode(array('success'=>True,'message'=>$msg,'table_info'=>$table_info));
	}
	
	//LOAN IMPORT DATA AND VALIDATION PARTS START
	public function do_loan_excel_import($import_id){
		$filename = dirname(__FILE__)."/php_excel/PHPExcel/IOFactory.php";
		include($filename);
		if($import_id < 0){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}
		$excel_path_qry    = 'select * from cw_import where import_id = "'.$import_id.'"';
		$excel_path_info   = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
		$excel_path_result = $excel_path_info->result();
		$excel_path_info->next_result();
		if(!$excel_path_result){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}else{
			$excel_file_path    = $excel_path_result[0]->excel_file_path;
			$module_id          = $excel_path_result[0]->module_id;
			$excel_format       = $excel_path_result[0]->excel_format;
			$excel_sheet_name   = (int)$excel_path_result[0]->excel_sheet_name;
			$excel_row_start    = (int)$excel_path_result[0]->excel_start_row;
			$excel_row_end      = (int)$excel_path_result[0]->excel_end_row;
			// FILTER KEY AND ENTITY SET AUDIT LOG _ARN 07-10-2025
			$filter_keys        = ["Excel Format"=>$excel_format ,"Sheet Name"=>$excel_sheet_name ];

			$format_qry 	    = 'select * from cw_util_excel_format where prime_excel_format_id = "'.$excel_format.'" and cw_util_excel_format.trans_status = 1';
			$format_info    = $this->db->query("CALL sp_a_run ('SELECT','$format_qry')");
			$format_rslt    = $format_info->result();
			$format_info->next_result();
			if(!$format_rslt){
				return json_encode(array('success' => false, 'message' => "Please add excel format before import"));
			}else{
				$exist_column_name  = explode(",",$format_rslt[0]->exist_column_name);
				$excel_format_qry 	= 'select IFNULL(pick_list_import,0) as pick_list_import,view_name,duplicate_data,picklist_data,field_type,pick_table,pick_list_type,pick_list,mandatory_field,field_isdefault,excel_line_column_name,excel_line_value from cw_util_excel_format_line inner join cw_form_setting on label_name = excel_line_column_name where excel_line_module_id = "'.$module_id.'" and prime_excel_format_id = "'.$excel_format.'" and cw_form_setting.prime_module_id = "'.$module_id.'" and cw_util_excel_format_line.trans_status = 1';		
				$excel_format        = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
				$excel_format_result = $excel_format->result();
				$excel_format->next_result();
				if(!$excel_format_result){
					return json_encode(array('success' => false, 'message' => "Please map excel cell column before import"));
				}else{
					try{
						$excel_obj = \PhpOffice\PhpSpreadsheet\IOFactory::load($excel_file_path);
					}catch(Exception $e){
						die('Error loading file "' . pathinfo($excel_file_path, PATHINFO_BASENAME). '": ' . $e->getMessage());
						return json_encode(array('success' => false, 'message' => "Invalid file or path"));
					}
					$sheet           = $excel_obj->getSheet($excel_sheet_name);
					if($excel_row_end){
						$total_rows = $excel_row_end;
					}else{
						$total_rows = $sheet->getHighestRow();
					}
					
					//LOAN DATA VALIDATION MANDATORY FILED AND 
					$err_column_array    = array();
					$err_column_tabview  = array();
					foreach($excel_format_result as $excel_info){
						$mandatory_field         = (int)$excel_info->mandatory_field;
						$field_type              = (int)$excel_info->field_type;
						$excel_line_column_name  = $excel_info->excel_line_column_name;
						$excel_line_value        = $excel_info->excel_line_value;
						$view_name               = $excel_info->view_name;
						$pick_table              = $excel_info->pick_table;
						$pick_list_type          = (int)$excel_info->pick_list_type;
						$pick_list               = $excel_info->pick_list;
						$picklist_data           = (int)$excel_info->picklist_data;
						$pick_list_import        = (int)$excel_info->pick_list_import;
						
						$common_multi_cell_value = $sheet->rangeToArray("$excel_line_value$excel_row_start:$excel_line_value$total_rows", NULL, TRUE, TRUE, TRUE);
						$i = $excel_row_start;
						foreach($common_multi_cell_value as $common_value){
							foreach($common_value as $col_key =>$col_value){
								if(empty($col_value) && !is_numeric($col_value)){
									$err_column_array['error']["$excel_line_value$i"] = $view_name;
									$msg_line = "columns are empty and invalid data is present please check it?";
									$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
								}elseif((int)$field_type === 5 || (int)$field_type === 7){
									if($pick_list_import !== 1){
										if($pick_list_type === 1){
											$pick_list_val   = explode(",",$pick_list);
											$pick_list_val_1 = $pick_list_val[0];
											$pick_list_val_2 = $pick_list_val[1];
											$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$col_value.'"';
											$pick_data  = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
											$pick_result = $pick_data->result();
											$pick_count  = $pick_data->num_rows();
											$pick_data->next_result();
											if((int)$pick_count === 0){
												$err_column_array['error']["$excel_line_value$i"] = $view_name;
												$msg_line = "column invalid data is present please check it?";
												$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
											}
										}
									}
								}elseif($field_type === 4){
									$excel_date     = $sheet->getCell("$excel_line_value$i")->getValue();	
									$unix_date      = $this->unix_convertion($excel_date);
									if($unix_date <= 0){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
											$msg_line = "Please enter valid date... Please map The Date Format Like (DD/MM/YYYY)";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}	
								}elseif($excel_line_column_name === "employee_code"){
									$emp_code_qry = 'select count(*) as rslt_count from cw_employees where trans_status = 1 and employee_code = "'.$col_value.'"';
									$emp_data     = $this->db->query("CALL sp_a_run ('SELECT','$emp_code_qry')");
									$emp_data_result = $emp_data->result();
									$emp_data->next_result();
									$rslt_count   = $emp_data_result[0]->rslt_count;
									if((int)$rslt_count === 0){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
										$msg_line = "employee code is not exit in employee master please check it?";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}
								}elseif($excel_line_column_name ==="loan_amount"){
									$col_value   = str_replace(',', '', $col_value);
									if(!is_numeric($col_value)){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
										$msg_line = "column invalid data is present please check it?";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}
								}elseif($excel_line_column_name ==="interest_rate"){
									if(!is_numeric($col_value)){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
										$msg_line = "column invalid data is present please check it?";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}
								}elseif($excel_line_column_name ==="number_of_installment"){
									if(!is_numeric($col_value)){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
										$msg_line = "column invalid data is present please check it?";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}
								}elseif($excel_line_column_name ==="per_month"){
									$col_value = str_replace(',', '', $col_value);
									if(!is_numeric($col_value)){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
										$msg_line = "column invalid data is present please check it?";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}
								}elseif($excel_line_column_name ==="total_amount"){
									$col_value = str_replace(',', '', $col_value);
									if(!is_numeric($col_value)){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
										$msg_line = "column invalid data is present please check it?";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}
								}
								$i++;
							}
						}
					}
					$err_status_array	    = array();
					for($row = $excel_row_start; $row <= $total_rows; $row++) {
						foreach($excel_format_result as $excel_info){
							$field_type             = (int)$excel_info->field_type;
							$excel_line_column_name = $excel_info->excel_line_column_name;
							$excel_line_value       = $excel_info->excel_line_value;
							$view_name              = $excel_info->view_name;
							$get_cell_value         = trim($sheet->getCell("$excel_line_value$row")->getCalculatedValue());
							if($excel_line_column_name === "emp_code"){
								$emp_code   = $get_cell_value;
								$doj_date_qry = 'select date_of_joining from cw_employees where trans_status = 1 and employee_code = "'.$emp_code.'"';
								$doj_date_data  = $this->db->query("CALL sp_a_run ('SELECT','$doj_date_qry')");
								$doj_date_result = $doj_date_data->result();
								$doj_date_data->next_result();
								$doj_date = $doj_date_result[0]->date_of_joining;
								$doj_date = strtotime($doj_date);
								$emp_line_val   = $excel_info->excel_line_value;
								$emp_view_name  = $view_name;
								
							}
							if($excel_line_column_name === "loan_date"){
								$loan_date_val   = $get_cell_value;
								if(!empty($loan_date_val)){
									$loan_cell_value = trim(Date::excelToDateTimeObject((int)$sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));
									$loan_date       = strtotime($loan_cell_value);
									$loan_line_val   = $excel_info->excel_line_value;
									$loan_view_name  = $view_name;
									$loan_date_value = date('m-Y', Date::excelToTimestamp($sheet->getCell("$excel_line_value$row")->getValue()));
								}
							}
							if($excel_line_column_name === "apply_year"){
								
								$apply_date_val   = $get_cell_value;
								if(!empty($apply_date_val)){
									$apply_month_line_val   = $excel_info->excel_line_value;
									$apply_month_view_name  = $view_name;
									$apply_cell_value       = trim(date('m-Y', Date::excelToTimestamp($sheet->getCell("$excel_line_value$row")->getValue())));
								}
							}
							if($excel_line_column_name === "category"){
								$category      = $get_cell_value;
								$cat_id_qry    = 'select prime_category_id from cw_category where trans_status = 1 and category_name  = "'.$category.'"';
								$cat_id_data   = $this->db->query("CALL sp_a_run ('SELECT','$cat_id_qry')");
								$cat_id_result = $cat_id_data->result();
								$cat_id_data->next_result();
								$cat_id        = $cat_id_result[0]->prime_category_id;
							}
							
							if($excel_line_column_name === "loan_amount"){
								$loan_amount         = $get_cell_value;
								$loan_amt_line_val   = $excel_info->excel_line_value;
								$loan_amt_view_name  = $view_name;
							}
							
							if($excel_line_column_name === "number_of_installment"){
								$no_of_install   = $get_cell_value;
							}
							
							if($excel_line_column_name === "per_month"){
								$per_month   = $get_cell_value;
							}
						}
						
						if($loan_date_value){
							$loan_date_qry = 'select count(*) as rslt_count from cw_transactions where trans_status = 1 and date_format(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y") , "%Y-%m") >= date_format(str_to_date(CONCAT("01-", "'.$loan_date_value.'"), "%d-%m-%Y") , "%Y-%m")';
							
							$loan_data  = $this->db->query("CALL sp_a_run ('SELECT','$loan_date_qry')");
							$loan_data_result = $loan_data->result();
							$loan_data->next_result();
							$loan_count = $loan_data_result[0]->rslt_count;
							if((int)$loan_count !== 0){
								$err_column_array['error']["$loan_line_val$row"] = $loan_view_name;
								$msg_line = "Payroll already processed this month, please check it?";
								$err_column_tabview['error']["$loan_line_val$row"]  = $loan_view_name." ".$msg_line;
								$err_status_array[] = "$excel_line_value$row";
							}
						}
						
						if($apply_cell_value){
							$apply_date_qry = 'select count(*) as rslt_count from cw_transactions where trans_status = 1 and date_format(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y") , "%Y-%m") >= date_format(str_to_date(CONCAT("01-", "'.$apply_cell_value.'"), "%d-%m-%Y") , "%Y-%m")';
							$apply_data  = $this->db->query("CALL sp_a_run ('SELECT','$apply_date_qry')");
							$apply_data_result = $apply_data->result();
							$apply_data->next_result();
							$apply_count = $apply_data_result[0]->rslt_count;
							if((int)$apply_count !== 0){
								$err_column_array['error']["$apply_month_line_val$row"] = $apply_month_view_name;
								$msg_line = "Payroll already processed this month, please check it?";
								$err_column_tabview['error']["$apply_month_line_val$row"]  = $apply_month_view_name." ".$msg_line;
								$err_status_array[] = "$excel_line_value$row";
							}
						}
						
						if($loan_date){
							if($loan_date < $doj_date){
								$err_column_array['error']["$loan_line_val$row"] = $loan_view_name;
								$msg_line = "loan date should not less than date of joining, please check it?";
								$err_column_tabview['error']["$loan_line_val$row"] = $msg_line;
								$err_status_array[] = "$excel_line_value$row";
							}
						}
						
						if($category && $emp_code){
							$emp_exit_qry    = 'select count(*) as exit_count from cw_employees where trans_status = 1 and employee_code    = "'.$emp_code.'" and role ="'.$cat_id.'"';
							$emp_exit_data   = $this->db->query("CALL sp_a_run ('SELECT','$emp_exit_qry')");
							$emp_exit_result = $emp_exit_data->result();
							$emp_exit_data->next_result();
							$emp_exit_count = $emp_exit_result[0]->exit_count;
							if((int)$emp_exit_count === 0){
								$err_column_array['error']["$emp_line_val$row"] = $emp_view_name;
								$msg_line = "Employee and category mismatched, please check it?";
								$err_column_tabview['error']["$emp_line_val$row"] = $msg_line;
								$err_status_array[] = "$excel_line_value$row";
							}
						}
						
						if($loan_amount && $no_of_install && $per_month){
							$tot_amount = 	(int)$no_of_install * (int)$per_month;
							if($tot_amount > $loan_amount){
								$err_column_array['error']["$loan_amt_line_val$row"] = $loan_amt_view_name;
								$msg_line = "Install amount is not greater than total amount, please check installment?";
								$err_column_tabview['error']["$loan_amt_line_val$row"] = $msg_line;
								$err_status_array[] = "$excel_line_value$row";
							}
						}
					}
					
					//LOAN DATA VALIDATION END
					$err_column_count = count($err_column_array['error'] ?? []);
					$err_column       = implode(",",$err_column_array['error'] ?? []);
					if((int)$err_column_count > 0) {
						$msg = "$err_column $msg_line";
						$table_info = $this->get_excel_error_ui($err_column_tabview);
						echo json_encode(array('success'=>false,'message'=>$msg,'table_info'=>$table_info));
						exit(0);
					}
					$status_array	    = array();
					$insert_sts	        = true;
					for($row =$excel_row_start; $row <= $total_rows; $row++){
						$prime_column_val = "";
						$prime_cell_val   = "";
						$exist_val        = "";
						$status_info = array();
						$status_info["Excel Row"] = $row;
						foreach($excel_format_result as $excel_info){
							$field_isdefault        = (int)$excel_info->field_isdefault;
							$mandatory_field        = (int)$excel_info->mandatory_field;
							$field_type             = (int)$excel_info->field_type;
							$pick_table             = $excel_info->pick_table;
							$pick_list_type         = (int)$excel_info->pick_list_type;
							$pick_list              = $excel_info->pick_list;
							$excel_line_column_name = $excel_info->excel_line_column_name;
							$excel_line_value       = $excel_info->excel_line_value;
							$get_cell_value         = trim($sheet->getCell("$excel_line_value$row")->getCalculatedValue());
							if($field_type === 4){
								$get_cell_value = trim(Date::excelToDateTimeObject((int)$sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));
								
							}elseif($field_type === 5){
								$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 '.$pick_list_val_2.' = "'.$get_cell_value.'"';
								$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
								$pick_result = $pick_data->result();
								$pick_count  = $pick_data->num_rows();
								$pick_data->next_result();
								$created_on  = date("Y-m-d H:i:s");
								if((int)$pick_count === 1){
									$pick_id        = $pick_result[0]->$pick_list_val_1;
									$pick_status    = (int)$pick_result[0]->trans_status;
									$get_cell_value = $pick_id;
								}
							}elseif($excel_line_column_name === "apply_year"){
								$get_cell_value = trim(date('m-Y', Date::excelToTimestamp($sheet->getCell("$excel_line_value$row")->getValue())));
							}
							if($field_isdefault === 1){
								$get_cell_value    = str_replace("'",'^', $get_cell_value);
								$prime_column_val .= $excel_line_column_name.",";
								$prime_cell_val   .= "'" . $get_cell_value . "',";
								if(empty($exist_column_name)) {
									if($mandatory_field === 1){
										$exist_val .= $excel_line_column_name.' = "'.$get_cell_value.'" and ';
									}
								}else{
									if(in_array($excel_line_column_name,$exist_column_name)){
										/*if($excel_line_column_name === "apply_year"){
											$excel_line_col_name = "install_year";
										}else{*/
											$excel_line_col_name = $excel_line_column_name;
										/*}*/
										$exist_val .= $excel_line_col_name.' = "'.$get_cell_value.'" and ';
									}
								}
							}
							if(in_array("$excel_line_value$row", $err_status_array)){
								$insert_sts	        = false;
							}else{
								$insert_sts	        = true;
							}
						}
						if($prime_column_val){
							$prime_id    = "prime_".$module_id."_id";
							$exist_val   = rtrim($exist_val," and ");
							$exist_query = "select count(*) exist_count from cw_loan where trans_status =1 and $exist_val";
							$exist_info   = $this->db->query("CALL sp_a_run ('RUN','$exist_query')");
							$exist_result = $exist_info->result();
							$exist_info->next_result();
							$exist_count = $exist_result[0]->exist_count;
							$created_on  = date("Y-m-d h:i:s");
							if((int)$exist_count === 0){
								if($insert_sts){
									$prime_column_val .= "trans_created_by,trans_created_date";
									$prime_cell_val   .= '"'.$this->logged_id.'",'.'"'.$created_on.'"';
									$prime_column_val  = rtrim($prime_column_val,",");
									$prime_cell_val    = rtrim($prime_cell_val,",");
									$prime_query       = "insert into $this->prime_table ($prime_column_val) VALUES ($prime_cell_val)";
									// SESSION SET AUDIT LOG _ARN 10-10-2025
									$this->session_setter($filter_keys,"Loan DATA ADD",'user');
									$this->db->query($prime_query);
									$loan_id               = $this->db->insert_id();
									$status_info['Status'] = "Inserted to DB";
									$this->installment_save($loan_id,$filter_keys);
									$status_array[]        = $status_info;
								}else{
									$status_info['Status'] = $err_column_tabview['error']["$emp_line_val$row"];
									$status_array[]        = $status_info;
								}
							}else{
								$status_info['Status'] = "Already Exist in DB";
								$status_array[] = $status_info;
							}
						}
					}
					$table_info = $this->get_excel_import_ui($status_array);
					echo json_encode(array('success'=>true,'message'=>"Successfully datas are imported",'table_info'=>$table_info));
				}
			}
		}
	}
	
	public function get_excel_import_ui($status_array){
		$table_info = "";
		$th_line    = "";
		$tr_line    = "";		
		$td_line    = "";
		$count      = 0;
		foreach($status_array as $status){
			$count++;
			$status_array_count  = count($status);
			$status_count = 0;
			foreach($status as $key => $value){
				$status_count++;
				if((int)$count === 1){
					$th_line .= "<th style='text-align:center !important;'>$key</th>";
				}
				$td_line .= "<td>$value</td>";	
				if((int)$status_count === (int)$status_array_count){
					$color = "style='color:#ff0303 !important;'";
					if($value === "Inserted to DB" || $value === "Updated to DB"){
						$color = "style='color:#15da15 !important;'";
					}
					$tr_line .= "<tr $color>$td_line</tr>";
					$td_line = "";
				}
			}
		}
		if($th_line !== ""){
			$table_info = "<table class='table table-bordered' style='text-align:center;' id='table_details'>
								<thead>
									<tr>
										$th_line
									</tr>
								</thead>
								<tbody>
									$tr_line
								</tbody>
						   </table>";
		}
		return $table_info;
	}

	//ERROR COLUMN AND ROW DISPLAY FOR INVALID DATAS
	public function get_excel_error_ui($err_column_tabview){
		$table_info = "";
		$th_line = "";
		$tr_line = "";
		foreach($err_column_tabview as $type => $err_column){
			$clr = 'green';
			if($type === 'error'){
				$clr = 'red';
			}
			foreach($err_column as $key => $value){
				$tr_line .= "<tr><td style='color:$clr !important;'>$key</td><td style='color:$clr !important;'>$value</td></tr>";
			}
		}
		$table_info = "<table class='table table-bordered' id='table_details'>
		<thead>
		<tr>
		<th>Row and Column</th>
		<th>Input Column</th>
		</tr>
		</thead>
		<tbody>
		$tr_line
		</tbody>
		</table>";
		return $table_info;
	}
	
function filterArray($value){
    return ($value == 2);
}

public function update_grants($ins_id,$emp_perm_grants_arr,$filter_keys){
	//array to string conversion without using foreach
	$qry_val_arr = [];
	array_walk_recursive($emp_perm_grants_arr, function($val,$key) use (&$qry_val_arr) {
		if($key !== "prime_employee_permission_id" && $key !== "role" && $key !== "trans_created_by" && $key !== "trans_created_date" && $key !== "trans_updated_by" && $key !== "trans_updated_date" && $key !== "trans_deleted_by" && $key !== "trans_deleted_date" && $key !== "trans_status"){
			$qry_val_arr[] = '"'.$val.'"';
		}else
		if($key === "trans_status"){
			$qry_val_arr[] = '"),("';
		}
	});
	$qry_val      = implode(',', $qry_val_arr ?? []);
	$ins_values   =  rtrim(str_replace('),(",',$ins_id.'"),(',$qry_val),'"),("');
	$sel_grants_qry  = 'select count(*) as count from cw_grants where prime_employees_id = "'.$ins_id.'"';
	$sel_grants_info =  $this->db->query("CALL sp_a_run ('SELECT','$sel_grants_qry')");
	$sel_grants_rslt = $sel_grants_info->result();
	$sel_grants_info->next_result();
	$count           = (int)$sel_grants_rslt[0]->count;	
	if($count){
		$del_grants_qry  = 'DELETE FROM cw_grants WHERE prime_employees_id = "'.$ins_id.'"';
		// =================== UPDATE GRANTS DATAS ON THAT EMPLOYEE ARN 10-02-2026=============
		$this->session_setter($filter_keys,"Grants DATA DELETE",'');
		$this->db->query($del_grants_qry);	
	}
	

	$ins_values     = $ins_values.'","'.$ins_id.'"';
	if(isset($ins_values)){
		$insert_grants_qry  = "INSERT INTO cw_grants (`permission_id`, `grants_menu_id`, `grants_sub_menu_id`, `access_add`, `access_update`, `access_delete`, `access_search`, `access_export`, `access_import`, `prime_employees_id`) VALUES ($ins_values)";
		// =================== UPDATE GRANTS DATAS ON THAT EMPLOYEE ARN 10-02-2026=============
		$this->session_setter($filter_keys,"Grants DATA ADDED",'user');
		$this->db->query($insert_grants_qry);
		$insert_id            = $this->db->insert_id();
		if($insert_id){
			return true;
		}else{
			return false;
		}
	}
}
/* USED IN BOTH EMPLOYEE AND CUSTOMER MODULE - END*/

//get notification details about fileds

public function get_notification(){
	$remainder_query    = $this->db->query("select * from cw_payroll_remainder where cw_payroll_remainder.trans_status =1 order by cw_payroll_remainder.prime_payroll_remainder_id asc");
	return $remainder_query->result();
}

//notification list and details MRJ --updates
public function get_notification_count(){
	$remainder_query    = $this->db->query("select * from cw_payroll_remainder where cw_payroll_remainder.trans_status =1 order by cw_payroll_remainder.prime_payroll_remainder_id asc");
	$remainter_rslt = $remainder_query->result();
	$remainder_name = array();
	foreach($remainter_rslt as $remainder){
		$remainder_column  = $remainder->remainder_field;
		$days_before       = $remainder->number_of_days;
		$remainder_head    = $remainder->remainder_heading;
		$start_date        = date('m-d');
		$end_date          = date("m-d", strtotime("+$days_before day"));
		$employees_data_qry = 'select '.$remainder_column.',employee_code,emp_name from cw_employees where trans_status = 1 and role !=1 and DATE_FORMAT('.$remainder_column.', "%m-%d") BETWEEN "'.$start_date.'" and "'.$end_date.'"';
		$employees_data_info = $this->db->query("CALL sp_a_run ('SELECT','$employees_data_qry')");
		$employees_result    = $employees_data_info->result();
		$employees_data_info->next_result();
		$employees_count   = $employees_data_info->num_rows();
		$remainder_name[$remainder_column] = array('remainder_column' => $remainder_column,'days_before' => $days_before,'remainder_head' => $remainder_head,'remainder_count'=>$employees_count);
	}
	return $remainder_name;
}
//get all insert emp id
public function get_trans_array($formula_process){	
	$trans_array = array();
	foreach($formula_process as $key => $value){
		$emp_data_query = 'select * from '.$this->prime_table.' where cw_employees.trans_status=1 and cw_employees.employee_code = "'.$value.'"';
		$emp_data_info   = $this->db->query("CALL sp_a_run ('RUN','$emp_data_query')");
		$emp_data_result = $emp_data_info->result_array();
		$emp_data_info->next_result();
		$trans_array[$value] = $emp_data_result[0];
	}
	return $trans_array;
}
		
public function create_formula_file(){
	$filename = dirname(__FILE__)."/"."Formula_model.php";
	$filename = str_replace('controllers','models',$filename);
	$can_process = false;
	if(file_exists($filename)){
		$created_date     = date("Y-m-d H:i:s",filemtime($filename));
		$isupdated_qry    = 'SELECT count(*) as tot_count FROM cw_form_bind_input WHERE trans_created_date >= "'.$created_date.'" or trans_updated_date >= "'.$created_date.'"';
		$isupdated_data   = $this->db->query("CALL sp_a_run ('SELECT','$isupdated_qry')");
		$isupdated_result = $isupdated_data->result();
		$isupdated_data->next_result();
		$tot_count = (int)$isupdated_result[0]->tot_count;
		if((int)$tot_count > 0){
			$can_process = true;
		}else{
			$can_process = false;
		}
	}else{
		$can_process = true;
	}
	if($can_process){
		$category_info   = $this->db->query("CALL sp_a_run ('select','select * from `cw_category` where trans_status = 1')");
		$category_result    = $category_info->result();
		$category_info->next_result();
		$import_formula = array();
		foreach($category_result as $category){
			$category_id   = $category->prime_category_id;
			$category_name = $category->category_name;
			$input_query = 'select * from cw_form_bind_input inner join cw_form_condition_formula on cw_form_condition_formula.prime_cond_id = cw_form_bind_input.input_cond_id where cw_form_bind_input.trans_status= 1 and cw_form_condition_formula.trans_status = 1 and input_cond_module_id = "employees" and FIND_IN_SET("'.$category_id.'",condition_for) order by cond_order asc';
			$input_data   = $this->db->query("CALL sp_a_run ('SELECT','$input_query')");
			$input_result = $input_data->result();
			$input_data->next_result();
			$line_input_bind_col = "";
			$line_input = "";
			foreach($input_result as $input){
				$line_input_bind_to      = $input->line_input_bind_to;
				$line_input_bind_col     = $input->line_input_bind_col;
				$is_drop_down            = $input->is_drop_down;
				$cond_drop_down          = $input->cond_drop_down;
				$line_input_bind_table   = $input->line_input_bind_table;
				$condition_check_form    = $input->condition_check_form;
				$condition_check_form    = explode(",",$condition_check_form);
				$line_input_bind_col     = str_replace("~","'",$line_input_bind_col);
				$line_input_bind_col     = str_replace("!",'"',$line_input_bind_col);
				if($line_input_bind_col){
					foreach($condition_check_form as $check_form){
						if(strpos($line_input_bind_col,"@$check_form@") !== false) {
							$preg_match      = preg_match('#\@(.*?)\@ (months|years)#', $line_input_bind_col);
							if($preg_match){
								$pattern = '/\@(.*?)\@ (months|years)/i';
								$replacement = '".$trans[\'${1}\']." ${2}';
								$match_line =  preg_replace($pattern, $replacement, $line_input_bind_col);
								$value = "\$trans['".$check_form."']";
								$line_input_bind_col = str_replace("@$check_form@",$value, $match_line);
							}
							$value = "\$trans['".$check_form."']";
							$line_input_bind_col = str_replace("@$check_form@",$value, $line_input_bind_col);
							$line_input_bind_col = str_replace("return","\$trans['$line_input_bind_to']=", $line_input_bind_col);
						}
					}
				}
				if($is_drop_down == 1){
					if($line_input_bind_col){
						$line_input_bind_col = "\n\t\t\t\tif((int)\$trans['".$cond_drop_down."'] === ".$line_input_bind_table."){\n\t\t\t\t\t".$line_input_bind_col."\n\t\t\t\t}";
						$line_input .= $line_input_bind_col;
					}else{
						$line_input = "";
					}
				}else{
					$line_input = $line_input_bind_col;
				}
				
				$import_formula[$category_id][$line_input_bind_to] = array("formula"=>$line_input);
			}
		}
		$formula_code = "";
		foreach($import_formula as $cat => $formulas){
			$formula_line = "";
			foreach($formulas as $key => $value){
				$formula_line    .= $value['formula'];
			}
			$formula_code .= "\n\t\t\t".'if((int)$trans["role"] === '.$cat."){\n\t\t\t\t$formula_line\n\t\t\t}";
		}	
		$emp_code    = "\n\t\t\t".'$employee_code = $trans["employee_code"];';
		$import_code = "\n\t\t".'foreach($trans_array as $trans){'.$emp_code.$formula_code."\n\t\t \$trans_array[\$employee_code] = \$trans;\n\t\t} \n\t\t";
		$fname = "import_formula(\$trans_array){";
		$final_code    = "<?php\nclass Formula_model extends CI_Model{\n\tpublic function $fname $import_code \n\t\treturn \$trans_array;\n\t}\n}\n?>";
		$formula_temp_file = dirname(__FILE__)."/"."Formula_model.php";
		$formula_temp_file = str_replace('controllers','models',$formula_temp_file);
		fopen("$formula_temp_file", "w");
		file_put_contents("$formula_temp_file",$final_code);
		chmod($formula_temp_file, 0777);
	}
}

//ESI STATUS UPDATED DYNAMIC BASED ON STATUS
	public function esi_statutory(){
		$get_emp_info_qry      ='select employee_code,role from cw_employees where trans_status = 1';
		$get_emp_data    = $this->db->query("CALL sp_a_run ('SELECT','$get_emp_info_qry')");
		$get_emp_result  = $get_emp_data->result();
		$get_emp_data->next_result();
		foreach($get_emp_result as $emp_rslt){
			$role          = $emp_rslt->role;
			$employee_code = $emp_rslt->employee_code;
			$get_esi_stat_qry      = 'select esi_limit,esi_eligibilit_formula from cw_statutory where trans_status = 1 and category = "'.$role.'"';
			$esi_statutory_data    = $this->db->query("CALL sp_a_run ('SELECT','$get_esi_stat_qry')");
			$esi_statutory_result  = $esi_statutory_data->result();
			$esi_statutory_data->next_result();
			if($esi_statutory_result){
				$esi_limit        = $esi_statutory_result[0]->esi_limit;
				$esi_elig_formula = $esi_statutory_result[0]->esi_eligibilit_formula;
				$esi_elig_formula = str_replace('@', '', $esi_elig_formula);
				$esi_elig_query = 'SELECT '.$esi_elig_formula.' AS esi_elig_amt FROM cw_employees WHERE trans_status = 1 and employee_code = "'.$employee_code.'"';
				$esi_elig_data    = $this->db->query("CALL sp_a_run ('SELECT','$esi_elig_query')");
				$esi_elig_result  = $esi_elig_data->result();
				$esi_elig_data->next_result();
				$esi_elig_amt = $esi_elig_result[0]->esi_elig_amt;
				if($esi_elig_amt > $esi_limit){
					$upd_esi_elig_query  = 'UPDATE cw_employees SET esi_eligibility = 2 WHERE trans_status = 1 and employee_code="'.$employee_code.'"';
				}else{
					$upd_esi_elig_query  = 'UPDATE cw_employees SET esi_eligibility = 1 WHERE trans_status = 1 and employee_code="'.$employee_code.'"';
				}
				$this->db->query("CALL sp_a_run ('UPDATE','$upd_esi_elig_query')");
			}
		}
		return true;
	}
	/* ==============================================================*/
	/* =================== IMPORT OPERATION - END ===================*/
	/* ==============================================================*/
	
/* ==============================================================*/
/* ================== PRINT OPERATION - START ===================*/
/* ==============================================================*/

	//NEHA EDIT START
	public function sent_print($view_id){
		
		if($this->control_name === "offer_letter"){
			$cat_query = 'select category,template from cw_offer_letter where prime_offer_letter_id = "'.$view_id.'" and trans_status = "1"';
			$cat_data     = $this->db->query("CALL sp_a_run ('SELECT','$cat_query')");
			$cat_result = $cat_data->result();
			$cat_data->next_result();
			$category = $cat_result[0]->category;
			$print_doc_id = $cat_result[0]->template;
			$qry      =  ' and FIND_IN_SET("'.$category.'",print_info_for)';
		}else{
			$qry  ='';
			$print_query = 'select prime_print_info_id from cw_print_info where print_info_module_id = "'.$this->control_name.'" and trans_status = "1"'.$qry;
			$print_data   = $this->db->query("CALL sp_a_run ('SELECT','$print_query')");
			$print_result = $print_data->result();
			$print_data->next_result();
			$print_doc_id = $print_result[0]->prime_print_info_id;
		}		
		$data = $this->load_print_data($print_doc_id,$view_id);
		$path = $this->control_name ."/print";
		$data['control_name'] = $this->control_name;
		$this->load->view($path,$data);	
	}

	public function load_print_data($print_doc_id,$view_id){
		$data['print_sts'] = false;
		// WHILE CHANGE PRIME ID BASED GET TEMPALTE BY _ARN
		$design_qry    = 'select print_design,print_type from cw_print_design inner join cw_print_info on cw_print_info.prime_print_info_id=cw_print_design.print_design_for where cw_print_info.prime_print_info_id = "'.$print_doc_id.'" and cw_print_info.trans_status = 1';
		$design_data   = $this->db->query("CALL sp_a_run ('SELECT','$design_qry')");
		$design_result = $design_data->result();
		$design_data->next_result();
		$print_design    = $design_result[0]->print_design;
		$print_type      = $design_result[0]->print_type;
		if((int)$print_type === 4){
			$style = '';
		}else{
			$style  = "<style>
			table{
				border: 1px !important;
				border-collapse: collapse !important;
				empty-cells: show !important;
				max-width: 100% !important;
				font-size: 13px !important;
			}
			tbody {
				border: 1px !important;
				border-collapse: collapse !important; 
				empty-cells: show !important;
				max-width: 100% !important;
				font-size: 13px !important;
			}
			td, th {
				border: 1px solid #000 !important;
				font-size: 13px !important;
			}
			td.fr-thick,th.fr-thick {
				border-width: 2px !important;
			}
			table.fr-dashed-borders td, table.fr-dashed-borders th {
				border-style: dashed !important;
			}
			</style>";
		}
		$print_design  = $style."".$print_design;
		$print_design  = str_replace('~','"',$print_design);
		$block_qry    = 'select * from cw_print_block where print_block_for = "'.$print_doc_id.'" and trans_status = 1';
		$block_data   = $this->db->query("CALL sp_a_run ('SELECT','$block_qry')");
		$block_result = $block_data->result();
		$block_data->next_result();

		$table_join_qry  	= 'select line_prime_table,line_prime_col,line_join_type,line_join_table,line_join_col,line_sort,print_table_for_id from cw_print_table where trans_status = 1';
		$table_join_info   	= $this->db->query("CALL sp_a_run ('SELECT','$table_join_qry')");
		$table_join_rlst	= $table_join_info->result_array();
		$table_join_info->next_result();
		$table_join_rlst = array_reduce($table_join_rlst, function($result, $arr){	
		    $result[$arr['print_table_for_id']][] = $arr;
		    return $result;
		}, array());

		$form_qry     		= 'select prime_module_id,prime_form_id,view_name,label_name,field_type,pick_list_type,pick_list,pick_table,auto_prime_id,auto_dispaly_value from cw_form_setting where trans_status = "1"';
		$form_data   		= $this->db->query("CALL sp_a_run ('SELECT','$form_qry')");
		$form_result_array 	= $form_data->result_array();
		$form_data->next_result();
		$form_result_array 	= array_reduce($form_result_array, function($result, $arr){
		    $result[$arr['prime_module_id']][$arr['label_name']][] = $arr;
		    return $result;
		}, array());

		$where_qry    = 'select where_condition,where_for_id from cw_email_table_where where trans_status = 1';
		$where_data   = $this->db->query("CALL sp_a_run ('SELECT','$where_qry')");
		$where_result = $where_data->result_array();
		$where_data->next_result();
		$where_result = array_reduce($where_result, function($result, $arr){
		    $result[$arr['where_for_id']] = $arr;
		    return $result;
		}, array());

		$session_query      = 'select session_value from cw_session_value where session_for = 1 and trans_status = "1"';
		$session_data       = $this->db->query("CALL sp_a_run ('SELECT','$session_query')");
		$session_result     = $session_data->result();
		$session_data->next_result();

		foreach($block_result as $block){
			$prime_print_block_id  = $block->prime_print_block_id;
			$print_block_name      = $block->print_block_name;
			$print_block_type      = (int)$block->print_block_type;
			$print_block_table     = $block->print_block_table;
			$print_block_column    = $block->print_block_column;
			$suppressed_data       = $block->suppressed_data;
			$cumulative_data       = $block->cumulative_data;
			$table_result  		   = $table_join_rlst[$prime_print_block_id];
			$line_table_query      = "";
			$cutome_table_check    = array('transactions'=>'cw_transactions');
			foreach($table_result as $table){
				$line_prime_table      = $table['line_prime_table'];
				$line_prime_col        = $table['line_prime_col'];
				$line_join_type        = $table['line_join_type'];
				$line_join_table       = $table['line_join_table'];
				$line_join_col         = $table['line_join_col'];
				$line_sort             = $table['line_sort'];
				$module_name           = str_replace("cw_","",$line_prime_table);
				$prime_id              = "prime_".$module_name."_id";
				$join_module_name      = str_replace("cw_","",$line_join_table);
				$join_prime_id         = "prime_".$join_module_name."_id";
				if((int)$line_sort === 1){
					$line_prime_table  = " $line_prime_table ";
					$line_join_table   = " $line_join_table on $line_join_col = $line_prime_col";
					$line_table_query .= " $line_prime_table  $line_join_type join $line_join_table"; 
				}else{
					$line_table_query .= " $line_join_type join $line_join_table on $line_join_col = $line_prime_col "; 
				}
			}
			if(!$line_table_query){
				$module_name      = str_replace("cw_","",$print_block_table);
				$prime_id         = "prime_".$module_name."_id";
				$line_table_query = " $print_block_table ";
			}
			if(!$print_block_column){
				$print_block_column = "*";
			}else{
				$select_query = "";
				$select_ytd_query = "";
				$pick_query   = "";
				$map_column = explode(",",$print_block_column);
				foreach($map_column as $table_column){
					$map_column   = explode(".",$table_column);
					$table_name   = $map_column[0];
					$column 	  = $map_column[1];
					$control_name = str_replace('cw_',"",$table_name);
					if(($control_name === "transactions")||($control_name === "custom_employees")){
						$control_name 	= "employees";
					}
					$form_result 		= $form_result_array[$control_name][$column];
					foreach($form_result as $form){
						$prime_form_id  = (int)$form['prime_form_id'];
						$view_name      = $form['view_name'];
						$label_name     = $form['label_name'];
						$field_type     = (int)$form['field_type'];
						$pick_list_type = (int)$form['pick_list_type'];
						$pick_list      = $form['pick_list'];
						$pick_table     = $form['pick_table'];
						$auto_prime_id      = $form['auto_prime_id'];
						$auto_dispaly_value = $form['auto_dispaly_value'];
						if((int)$field_type === 4){
							$select_query .= 'DATE_FORMAT('.$table_name.'.'.$label_name.', "%d-%m-%Y") as '.$label_name.' , ';
						}else
						if(($field_type === 5) || ($field_type === 7)){
							if($pick_list_type === 1){
								$pick_list_val   = explode(",",$pick_list);
								$pick_list_val_1 = $pick_list_val[0];
								$pick_list_val_2 = $pick_list_val[1];
								
								$pick_query_as = $pick_table."_".$prime_form_id;
								$select_query .= "$pick_query_as.$pick_list_val_2 as $label_name , ";
								$pick_query .= " left join $pick_table as $pick_query_as on $pick_query_as.$pick_list_val_1 = $table_name.$label_name ";
							}else
							if($pick_list_type === 2){ 
								$pick_list_val_1 = $pick_table."_id";
								$pick_list_val_2 = $pick_table."_value";
								$pick_list_val_3 = $pick_table."_status";
								
								$pick_query_as = $pick_table."_".$prime_form_id;
								$select_query .= "$pick_query_as.$pick_list_val_2 as $label_name , ";
								$pick_query   .= " left join $pick_table as $pick_query_as on $pick_query_as.$pick_list_val_1 = $table_name.$label_name ";
							}
						}else
						if($field_type === 9){
							$pick_query_as = $pick_table."_".$prime_form_id;
							$select_query .= "$pick_query_as.$auto_dispaly_value as $label_name,";
							$pick_query .= " left join $pick_table as $pick_query_as on $pick_query_as.$auto_prime_id = $table_name.$label_name ";
						}else
						if(($field_type === 2) || ($field_type === 3)){
							$label_ytd  =	$label_name."_ytd";
							$select_ytd_query .= "sum($table_name.$label_name) as $label_ytd, ";
							$select_query .= "$table_name.$label_name , ";
						}else{
							$select_query .= "$table_name.$label_name , ";
						}
					}					
				}
			}
			$where_trans = "";
			$where_trans_info = explode(",",$print_block_table);
			foreach($where_trans_info as $trans_info){
				if($trans_info === "cw_transactions"){
					$select_query .= "cw_transactions.transactions_month , ";
				}				
				$where_trans .= "$trans_info.trans_status = 1 and ";
			}
			$where_trans 	 = rtrim($where_trans,'and ');
			$where_condition = "";
			if($where_result){
				$where_condition = str_replace('^','"',$where_result[0]->where_condition);
				$where_condition = str_replace('@logged_id@',$view_id,$where_condition);				
				$session_date_list  = array("logged_DMY"=>"d-m-Y","logged_YMD"=>"Y-m-d","logged_MY"=>"m-Y","logged_YM"=>"Y-m","logged_Y"=>"Y"); 
				foreach($session_result as $rslt){
					$session_value 	   = $rslt->session_value;
					if($session_value !== "access_data"){
						$exist_val = "@".$session_value."@";
						if($session_date_list[$session_value]){
							$date_formate      = $session_date_list[$session_value];
							$saved_session_val = date($date_formate);
						}else{
							$saved_session_val = $this->session->userdata($session_value);
						}
						$where_condition  = str_replace($exist_val,$saved_session_val,$where_condition);
					}
				}
			}
			$select_query = rtrim($select_query,',');
			$select_query = rtrim($select_query,' , ');
			if((int)$cumulative_data === 1){
				$start_fin_date = $this->financial_info[0]->start_date;
				$start_fin_date = date('m-Y',strtotime($start_fin_date));
				$end_fin_date   = $this->financial_info[0]->end_date;
				$end_fin_date   = date('m-Y',strtotime($end_fin_date));
				$select_ytd_query = rtrim($select_ytd_query,',');
				$select_ytd_query = rtrim($select_ytd_query,' , ');
				$where_ytd_condition  = ' and date_format(str_to_date(transactions_month, "%m-%Y") , "%Y-%m")  >= date_format(str_to_date("'.$start_fin_date.'", "%m-%Y"), "%Y-%m") and date_format(str_to_date(transactions_month, "%m-%Y") , "%Y-%m")  <= date_format(str_to_date("'.$end_fin_date.'", "%m-%Y"), "%Y-%m")';
				$final_ytd_qry = "select $select_ytd_query from $line_table_query $pick_query  where $where_trans $where_condition  $where_ytd_condition";
				$final_ytd_data   = $this->db->query("CALL sp_a_run ('SELECT','$final_ytd_qry')");
				$final_ytd_result = $final_ytd_data->result();
				$final_ytd_data->next_result();
				foreach($final_ytd_result as $ytd_rslt){
					$map_column = explode(",",$print_block_column);
					foreach($map_column as $table_column){
						$map_column   = explode(".",$table_column);
						$ytd_column 	  = $map_column[1]."_ytd";
						$ytd_value        = $ytd_rslt->$ytd_column;
						$replace_ytd_val  = "@".$ytd_column."@";
						$print_design  = str_replace($replace_ytd_val,$ytd_value,$print_design);
					}
				}
			}
			$final_qry = "select $select_query from ".$line_table_query." $pick_query where $prime_id = ".$view_id." and $where_trans $where_condition";
			$final_data   = $this->db->query("CALL sp_a_run ('SELECT','$final_qry')");
			$final_result = $final_data->result();
			$final_data->next_result();
			$tr_line = "";
			$th_line = "";
			$count = 0;
			$assign_date_formate_list  = array("DMY"=>"d-m-Y","YMD"=>"Y-m-d","DFY"=>"d F Y","MY"=>"F-Y","YM"=>"Y-F","D"=>"d","M"=>"M","Y"=>"Y");
			$split_qry    = 'select * from cw_print_split where trans_status = 1 and split_table_info ="'.$print_doc_id.'"';
			$split_data   = $this->db->query("CALL sp_a_run ('SELECT','$split_qry')");
			$split_result = $split_data->result();
			$split_data->next_result();
			$split_array = array();
			foreach($split_result as $split){
				$split_info  = $split->split_info;
				$split_colum = $split->split_colum;
				$split_array[$split_colum] = $split_info;
			}		
			if($final_result){
				$data['print_sts'] = true;
				foreach($final_result as $rslt){
					$count++;
					$map_column = explode(",",$print_block_column);
					$td_line = "";
					foreach($map_column as $table_column){
						$map_column   = explode(".",$table_column);
						$column 	  = $map_column[1];
						$value        = $rslt->$column;
						
						if($column === 'date_of_joining'){
							$value        = $rslt->$column;
							$date_of_join = $value;
						}else
						if($column === 'last_working_date'){
							$value          = $rslt->$column;
							$last_work_date = $value;
						}
						$replace_val  = "@".$column."@";
						//amount number is changed to in words for net pays--07SEP2019
						if($column == 'net_pay'){
							$value         = $rslt->$column;
							$print_design  = str_replace($replace_val,$value,$print_design);
							$net_pay_val   = $value;
							$net_pay_words = $this->numbertowords($net_pay_val);
							$net_pay_words = strtoupper($net_pay_words);
							$print_design  = str_replace("@net_pay_words@",$net_pay_words,$print_design);
						}else
						if($column == 'employee_name'){
							$value         = ucwords($rslt->$column);
							$print_design  = str_replace($replace_val,$value,$print_design);
						}else
						if($column === 'total_experience'){
							$total_exp 	   = $this->years_calculate($date_of_join,$last_work_date);
							$print_design  = str_replace($replace_val,$total_exp,$print_design);
						}else
						if($column == 'reporting_person'){
							$value         = ucwords($rslt->$column);
							$print_design  = str_replace($replace_val,$value,$print_design);
						}else
						if($column == 'salary'){
							$value         = $rslt->$column;
							$print_design  = str_replace($replace_val,$value,$print_design);
							$salary_val   = $value;
							$salary_words = $this->numbertowords($salary_val);
							$salary_words = ucwords($salary_words);
							$print_design  = str_replace("@salary_words@",$salary_words,$print_design);
						}
						
						if($split_array[$replace_val]){
							//Process split informtion 
							$process_function = $split_array[$replace_val];
							if((int)$process_function === 1){
								$transactions_month = $final_result[0]->transactions_month;
								$employee_code      = $final_result[0]->employee_code;
								$loan_info = $this->get_loan_value($transactions_month,$employee_code);
								$print_design = str_replace($replace_val,$loan_info,$print_design);
							}
						}else{
							if($print_block_type === 1){
								$print_design = str_replace($replace_val,$value,$print_design);
								foreach($assign_date_formate_list as $key=>$formate){
									if($column == 'transactions_month'){//transactions month static updated
										$start         = "@".$key."_";
										$end           = "_".$key."@";
										$replace_val   = $start.$column.$end;
										$value         = date('Y-m-d',strtotime("01-".$rslt->$column));
										$date_value    = date_create($value);
										$replace_value = strtoupper(date_format($date_value,$formate));
										$print_design  = str_replace($replace_val,$replace_value,$print_design);
									}else{//not static month updated
										$start         = "@".$key."_";
										$end           = "_".$key."@";
										$replace_val   = $start.$column.$end;
										$replace_val   = $start.$column.$end;
										$date_value    = date_create($value);
										if($date_value instanceof DateTimeInterface) {
											$replace_value = date_format($date_value, $formate);
										} else {
											$replace_value = ''; // fallback
										}
										// $replace_value = date_format($date_value,$formate);
										$print_design  = str_replace($replace_val,$replace_value,$print_design);
									}
								}
							}else
							if($print_block_type === 2){
								$td_line .= "<td style='text-align:center;'>$value</td>";
							}
							if($count === 1){
								$head_name = ucwords(str_replace("_"," ",$column));
								$th_line .= "<th style='text-align:center;'>$head_name</th>";
							}
						}
					}
					if($print_block_type === 2){
						if($count === 1){
							$th_line  = "$th_line";
						}
						$tr_line .= "<tr>$td_line</tr>";
					}
				}
				if($print_block_type === 2){
					$table_list  = "<table style='width:100%;'><thead>$th_line</thead><tbody>$tr_line</tbody></table>";
					$replce_block = "@".strtolower(str_replace(" ","_",$print_block_name))."@";
					$print_design = str_replace($replce_block,$table_list,$print_design);
				}
			}
			$data['suppressed_data'] = $suppressed_data;
		}
		// $print_design = str_replace("<br>","",$print_design);
		$print_design         = str_replace("@today_date@",date("d-m-Y"),$print_design);
		$data['print_design'] = $print_design;
		return $data;
	}
	//NEHA EDIT END
	
	//number to words changed in payslip
	public function numbertowords($number){
		$prefix = "";
		if($number < 0){
			$prefix = "-";
			$number = ltrim($number,"-");
		}
		$no       = round($number);
		$point    = round($number - $no, 2) * 100;
		$hundred  = null;
		$digits_1 = strlen($no);
		$i = 0;
		$str = array();
		$words = array('0' => '', '1' => 'One', '2' => 'Two',
			'3' => 'Three', '4' => 'Four', '5' => 'Five', '6' => 'Six',
			'7' => 'Seven', '8' => 'Eight', '9' => 'Nine',
			'10' => 'Ten', '11' => 'Eleven', '12' => 'Twelve',
			'13' => 'Thirteen', '14' => 'Fourteen',
			'15' => 'Fifteen', '16' => 'Sixteen', '17' => 'Seventeen',
			'18' => 'Eighteen', '19' =>'Nineteen', '20' => 'Twenty',
			'30' => 'Thirty', '40' => 'Forty', '50' => 'Fifty',
			'60' => 'Sixty', '70' => 'Seventy',
			'80' => 'Eighty', '90' => 'Ninety');
		$digits = array('', 'Hundred', 'Thousand', 'Lakh', 'Crore');
		while ($i < $digits_1) {
			$divider = ($i == 2) ? 10 : 100;
			$number = floor($no % $divider);
			$no = floor($no / $divider);
			$i += ($divider == 10) ? 1 : 2;
			if ($number) {
				$plural = (($counter = count($str ?? [])) && $number > 9) ? '' : null;
				$hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
				$str [] = ($number < 21) ? $words[$number] .
				" " . $digits[$counter] . $plural . " " . $hundred
				:
				$words[floor($number / 10) * 10]
				. " " . $words[$number % 10] . " "
				. $digits[$counter] . $plural . " " . $hundred;
			} else $str[] = null;
		}
		$str = array_reverse($str);
		$result = implode('', $str ?? []);
		$points = ($point) ? "." . $words[$point / 10]. " ".$words[$point = $point % 10] : '';
		return $prefix.$result;
	}
	
	//Sheet Name display in import page
	public function sheet_name(){
		$encString = file_get_contents('php://input');
		$_POST     = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(['success'=>false,'message'=>'URL expired']);
			exit;
		}
		$file_path = $this->input->post('file_path');
		if(!$file_path || !file_exists($file_path)){
			echo json_encode(['success'=>false,'message'=>'File not found']);
			exit;
		}
		$sheet_name      = [];
		try{
			$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_path);
			$sheet_count = $spreadsheet->getSheetCount();
			for($i=0; $i<$sheet_count; $i++){
				$sheet        = $spreadsheet->getSheet($i);
				$sheet_name[] = $sheet->getTitle();
			}
		}catch(Exception $e){
			echo json_encode(['success'=>false,'message'=>'Invalid excel']);
			exit;
		}
		echo json_encode(['sheet_name'=>$sheet_name]);
	}
	
	public function get_loan_value($process_month,$employee_code){
		$process_month = explode("-",$process_month);
		$loan_month    = $process_month[0];
		$loan_year     = $process_month[1];
		$loan_qry = 'select emp_code,install_amount,cw_loan_type.loan_type from cw_loan_installment inner join cw_loan_type on  cw_loan_type.prime_loan_type_id = cw_loan_installment.loan_type where cw_loan_installment.trans_status = 1 and cw_loan_installment.emp_code ="'.$employee_code.'" and cw_loan_installment.install_year ="'.$process_month.'"';
		$loan_data   = $this->db->query("CALL sp_a_run ('SELECT','$loan_qry')");
		$loan_result = $loan_data->result();
		$loan_data->next_result();
		$loan_tr = "";
		foreach($loan_result as $loan){
			$loan_type      = $loan->loan_type;
			$install_amount = $loan->install_amount;
			$loan_tr .= "<tr>
			<td style='width:77%;'>$loan_type</td>
			<td>$install_amount</td>
			</tr>";
		}
		if($loan_tr !== ""){
			$loan_tr = "<table style='width:100%'>
			$loan_tr
			</table>";
		}
		return $loan_tr;
	}
	
	//IMPORT FILE VIEW INFORMATION
	public function import(){
		$data['encKey']        = $this->generateKey();
		$data['module_id']     = $this->control_name;		
		$excel_format_qry = 'select prime_excel_format_id,excel_name from cw_util_excel_format where excel_module_id = "'.$this->control_name.'" and trans_status = 1';
		$excel_format   = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
		$excel_result    = $excel_format->result();
		$excel_format->next_result();
		$excel_format_drop[""] = "---- Excel Format ----";
		foreach($excel_result as $excel){
			$prime_excel_format_id = $excel->prime_excel_format_id;
			$excel_name            = $excel->excel_name;
			$excel_format_drop[$prime_excel_format_id] = $excel_name;
		}
		$data['excel_format_drop'] = $excel_format_drop;
		
		$this->load->view("$this->control_name/import",$data);
	}
	public function rowset_remove_file(){
		$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);
		}
		$table_name  = $this->input->post('table_name_set');
		$row_id      = (int)$this->input->post('row_id');
		$input_name  = $this->input->post('input_name');
		$view_id     = (int)$this->input->post('view_id');
		$primes_id   = (int)$this->input->post('primes_id');
		$remove_cw   = str_replace("cw_","",$table_name);
		$primary_id  = "prime_".$remove_cw."_id";
		if($table_name){
			$created_on    = date("Y-m-d h:i:s");
			$set_query     = $input_name .' = "" ,trans_updated_by = "'. $this->logged_id .'",trans_updated_date = "'.$created_on.'"';
			$update_query  = 'UPDATE '.$table_name .' SET '. $set_query .' WHERE '.$primary_id.' = "'. $row_id .'"';
			$this->db->query("CALL sp_a_run ('UPDATE','$update_query')");
			$row_set_edit = $this->get_row_set_data($view_id,$primes_id);
			$div_id       = $row_set_edit['div_id'];
			$table_id     = $row_set_edit['table_id'];
			$row_set_view = $row_set_edit['row_set_view'];
			echo json_encode(array('success' => TRUE, 'message' => "Successfully updated",'div_id' => $div_id, 'table_id' => $table_id,'row_set_view'=>$row_set_view));
		}else{
			echo json_encode(array('success' => FALSE, 'message' => "Unable to process your request"));
		}
	}
	
	//NEHA EDIT START
	public function excel($Payload){
		//Decryption
		$_POST            = $this->cryptoDecrypt(base64_decode(urldecode($Payload)));
		$module_id        = $this->input->post('module_id');
		$excel_format     = $this->input->post('excel_format');
		$excel_format_qry = 'select excel_name,excel_line_column_name,excel_line_value from cw_util_excel_format_line inner join cw_util_excel_format on cw_util_excel_format.prime_excel_format_id = cw_util_excel_format_line.prime_excel_format_id where excel_line_module_id = "'.$module_id.'" and cw_util_excel_format_line.prime_excel_format_id ="'.$excel_format.'" and cw_util_excel_format_line.trans_status = 1 and cw_util_excel_format.trans_status = 1 GROUP BY excel_line_column_name';
		$excel_format     = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
		$excel_result     = $excel_format->result();
		$excel_format->next_result();

		if(!$excel_result){
       		 //  No mapping found → return toaster error response
			echo json_encode(array('success' => false,'message' => 'Please configure Excel mapping in Utilities settings'));
			exit(0);
		}

		// THIS FOR REPLACE COLUMN NAMES HAS VIEW NAME _ARN 02-12-2025
		if($module_id === "monthly_input"){
			$module_id = "employees";
		}

		$get_view_name_query  = 'SELECT view_name,label_name,prime_module_id FROM `cw_form_setting` WHERE trans_status = 1 and prime_module_id = "'.$module_id.'"';
		$column_info          = $this->db->query("CALL sp_a_run ('SELECT','$get_view_name_query')");
		$column_rslt          = $column_info->result_array();
		$column_info->next_result();

		$column_rslt = array_reduce($column_rslt, function ($result, $arr) {
		    $result[$arr['label_name']] = $arr['view_name'];
		    return $result;
		}, array());


		$excel_name 	= str_replace(' ', '_', $excel_result[0]->excel_name);
		$spreadsheet    = new Spreadsheet();
		$worksheet      = $spreadsheet->getActiveSheet();
		# Set the first row as the header row
		foreach($excel_result as $excel){
			$view_name        = $column_rslt[$excel->excel_line_column_name];
			$excel_line_value = $excel->excel_line_value;
			if(!$view_name){
				$view_name    = str_replace('_', ' ', $excel->excel_line_column_name);
			}
			$worksheet->getCell($excel_line_value.'1')->setValue($view_name);
		}
	    $filename = $excel_name.".xls";  
	    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); 
	    header('Content-Disposition: attachment;filename= "'.$filename.'"'); 
	    header('Cache-Control: max-age=0'); 
		$writer   = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
		$writer->save('php://output');
		echo json_encode(array('success' => TRUE, 'output' => $worksheet));
	    exit(0);
	}
	//NEHA EDIT END
	//Get Employee Date Of Joining for LEAVE MODULE
	public function get_employee_details(){
		$encString     = file_get_contents('php://input');
		$_POST         = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
		$employee_code          = $this->input->post('emp_code');		
		/* Custom Code for Weekoff Component */
		$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 = 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;
		$component        = $component_result[0]->label_name;		
		$emp_details_qry  = "";
		if($component){
			$emp_details_qry  = 'SELECT role as category,date_of_joining,department,first_level_approval,second_level_approval,approve_type,'.$component.',device_code from cw_employees WHERE employee_code = "'. $employee_code .'" and trans_status = 1';
		}else{
			$emp_details_qry  = 'SELECT role as category,date_of_joining,first_level_approval,second_level_approval,approve_type,device_code from cw_employees WHERE employee_code = "'. $employee_code .'" and  trans_status = 1';
		}
		$emp_details_info       = $this->db->query("CALL sp_a_run ('SELECT','$emp_details_qry')");
		$emp_details_rlst       = $emp_details_info->result();
		$emp_details_info->next_result();
		$date_of_joining        = date("d-m-Y",strtotime($emp_details_rlst[0]->date_of_joining));
		$first_level_approval   = $emp_details_rlst[0]->first_level_approval;
		$second_level_approval  = $emp_details_rlst[0]->second_level_approval;
		$component_value    	= $emp_details_rlst[0]->$component;
		$approve_type    	    = $emp_details_rlst[0]->approve_type;
		$category        	    = $emp_details_rlst[0]->category;
		$department        	    = $emp_details_rlst[0]->department;
		$device_code            = $emp_details_rlst[0]->device_code;
		
		//GET A FORM DATE AND TO DATE VALIDATION
		$salary_start_date     = "";
		$salary_end_date       = "";
		if($emp_details_rlst){
			if(!(int)$approve_type){
				echo json_encode(array('success' => FALSE, 'message' => "Leave Approval Should not Be Empty.. Please Contact HR..."));
				exit(0);
			}else
			if((int)$approve_type === 1 || (int)$approve_type === 2){
				if(!$first_level_approval){
					echo json_encode(array('success' => FALSE, 'message' => "Leave First Level Approval Not Mapped Please Contact HR..."));
					exit(0);
				}else
				if(!$second_level_approval){
					echo json_encode(array('success' => FALSE, 'message' => "Leave Second Level Approval Not Mapped Please Contact HR..."));
					exit(0);
				}
			}else
			if((int)$approve_type === 3){
				if(!$first_level_approval){
					echo json_encode(array('success' => FALSE, 'message' => "Leave First Level Approval Not Mapped Please Contact HR..."));
					exit(0);
				}
			}else
			if((int)$approve_type === 4){
				if(!$second_level_approval){
					echo json_encode(array('success' => FALSE, 'message' => "Leave Second Level Approval Not Mapped Please Contact HR.."));
					exit(0);
				}
			}
			//function for get a MONTH DAY RELATED INFORMATION
			/*$month_day_info        = $this->month_day_info($category);*/
			//DR FUNCTION FOR MONTH DAY (MIN DATE AND MAX DATE GET FUNCTION) FROM 5JUL22
			$month_day_info        = $this->tos_day_info($employee_code,"3"); // 3 => Leave Entry
			if(count($month_day_info ?? [])){ 
				$salary_start_date    = $month_day_info['salary_start_date'];
				$salary_end_date      = $month_day_info['salary_end_date'];
				$year_end_date        = $month_day_info['year_end_date'];
				$starting_date        = $month_day_info['starting_date'];
				$ending_date          = $month_day_info['ending_date'];

				echo json_encode(array('success' => TRUE, 'category' => $category, 'date_of_joining' => $date_of_joining, 'department' => $department,  'first_level_approval' => $first_level_approval, 'second_level_approval' => $second_level_approval, 'component_value' => $component_value, 'device_code' => $device_code, 'approve_type' => $approve_type, 'salary_start_date' => $salary_start_date, 'salary_end_date' => $year_end_date, 'fin_start_date' => date("d-m-Y",strtotime($starting_date)), 'fin_end_date' => date("d-m-Y",strtotime($ending_date))));
			}else{
				echo json_encode(array('success' => FALSE, 'message' => "Please Set Month Day for this Category..."));
				exit(0);
			}
		}else{
			echo json_encode(array('success' => FALSE, 'message' => "Please try after Sometime..."));
		}
	}
	public function emp_details($employee_code){
		/* Custom Code for Weekoff Component */
		$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 = 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;
		$component        = $component_result[0]->label_name;		
		$emp_details_qry  = "";
		if($component){
			$emp_details_qry  = 'SELECT role as category,date_of_joining,department,first_level_approval,second_level_approval,approve_type,'.$component.',device_code from cw_employees WHERE employee_code = "'. $employee_code .'" and trans_status = 1';
		}else{
			$emp_details_qry  = 'SELECT role as category,date_of_joining,first_level_approval,second_level_approval,approve_type,device_code from cw_employees WHERE employee_code = "'. $employee_code .'" and  trans_status = 1';
		}
		$emp_details_info     = $this->db->query("CALL sp_a_run ('SELECT','$emp_details_qry')");
		$emp_details_rlst     = $emp_details_info->result();
		$emp_details_info->next_result();
		return $emp_details_rslt;	
	}

	//COMMON MONTH DAY QUERY FUNCTION
	public function month_day_qry_fun($category){
		$month_day_qry         = 'SELECT category,day_conditions,day_count,day_start,day_end from cw_month_day where cw_month_day.category = "'.$category.'" and cw_month_day.trans_status = 1';
		$month_day_info        = $this->db->query("CALL sp_a_run ('SELECT','$month_day_qry')");
        $month_day_result      = $month_day_info->result();
        $month_day_info->next_result();
        return $month_day_result;
	}
	//PAYROLL PROCESS WISE SALARY START DATE AND END DATE GET
	public function month_day_info($category){
		//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));	
		$ending_date            = date('Y-m-d',strtotime($financial_info[0]->ending_date));	
		$month_day_result       = $this->month_day_qry_fun($category);
		if($month_day_result){
			$day_conditions    = $month_day_result[0]->day_conditions;
			$day_count         = $month_day_result[0]->day_count;
			$day_start         = "";
			$day_end           = "";
			$process_month     = "";
			$next_month        = "";

			//GET A EMPLOYEE CODE AND PROCESS MONTH FORM LEAVE EXPORT MODULE
			$payroll_posting_query  = 'SELECT role as category,date_format(MAX(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y")) , "%m-%Y") AS process_month from cw_transactions where cw_transactions.role ="'.$category.'" and cw_transactions.trans_status = 1';			
			$payroll_posting_info   = $this->db->query("CALL sp_a_run ('SELECT','$payroll_posting_query')");
	        $payroll_posting_result = $payroll_posting_info->result();
	        $payroll_posting_info->next_result();
	        $process_month          =  $payroll_posting_result[0]->process_month;

	       if(!$process_month){
	        	$process_month = date("m-Y",strtotime($starting_date));
				$day_start     = date('d',strtotime($starting_date));
				$day_end       = date('d',strtotime($ending_date));
	        }else{
	        	$next_month    = date('m-Y',strtotime("+1 month",strtotime("01-".$process_month)));
				if((int)$day_conditions === 3){
					//GET LAST DATE FOR CUTTOFF TYPE ONLY
					$day_start      = $month_day_result[0]->day_start;
					$day_end        = $month_day_result[0]->day_end;					
				}else{
					$day_start     = '01';
					$day_end       = date('t',strtotime("01-".$next_month));
				}
			}
			$today_date        = date('d-m-Y');
			$salary_end_year   = "12-".date('Y');
			if($day_conditions === "" || $day_start === "" || $day_end === ""){
				return false;
			}else{
				if((int)$day_conditions === 3){
					$sal_start         = $day_start;
					//For Current month between days increment
					$date              = new DateTime("01-$next_month 00:00:00");
					$date->modify('-1 month');
					$salary_start_date = $date->format("$sal_start-m-Y");	
					$salary_end_date   = date('d-m-Y',strtotime("$day_end-".$next_month));
					$year_end_date     = date("d-m-Y",strtotime($ending_date));
				}else{
					$sal_start         = $day_start;
					// $sal_start = '01';
					$date              = new DateTime("01-$next_month 00:00:00");
					$salary_start_date = $date->format("$sal_start-m-Y");	
					$salary_end_date   = date("d-m-Y",strtotime($day_end."-".$next_month));
					$year_end_date     = date("d-m-Y",strtotime($ending_date));
				}
				$month_day_arr      = array("salary_start_date" => $salary_start_date,"salary_end_date" => $salary_end_date,"year_end_date" => $year_end_date,"starting_date" => $starting_date,"ending_date" => $ending_date);
				return $month_day_arr;
			}
		}else{
			return false;
		}
	}
	//PROCESS MONTH WISE SALARY START DATE AND END DATE GET
	public function salary_start_end_info($category,$process_month){
		$month_day_result      = $this->month_day_qry_fun($category);
		if($month_day_result){
			$day_conditions    = $month_day_result[0]->day_conditions;
			$day_count         = $month_day_result[0]->day_count;
			$day_start         = $month_day_result[0]->day_start;
			$day_end           = $month_day_result[0]->day_end;
			
			if((int)$day_conditions === 3){
				$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("$sal_start-m-Y");	
				$salary_end_date   = date('d-m-Y',strtotime("$day_end-".$process_month));
			}else{
				$sal_start         = '01';
				$day_end           = $day_count;
				if((int)$day_conditions === 2){
					$day_end           = date('t',strtotime("01-".$process_month));
				}
				$date              = new DateTime("01-$process_month 00:00:00");
				$salary_start_date = $date->format("$sal_start-m-Y");	
				$salary_end_date   = date("d-m-Y",strtotime($day_end."-".$process_month));
			}
			$sal_start_end_arr     = array("salary_start_date" => $salary_start_date,"salary_end_date" => $salary_end_date);
			return $sal_start_end_arr;
		}
	}	
	//CURL GET METHOD TO FETCH MASTER DATA
	public function curl($post_url,$post_data=null){
		$curl = curl_init();
		curl_setopt_array($curl, array(
		  CURLOPT_URL => $post_url,
		  CURLOPT_RETURNTRANSFER => true,
		  CURLOPT_ENCODING => "",
		  CURLOPT_MAXREDIRS => 10,
		  CURLOPT_TIMEOUT => 0,
		  CURLOPT_FOLLOWLOCATION => true,
		  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		  CURLOPT_CUSTOMREQUEST => "POST",
		  CURLOPT_POSTFIELDS => $post_data,
		));
		$response = curl_exec($curl);
		curl_close($curl);		
		return $response;
	}

	// GENERATE PDF
	public function generate_pdf($table_data,$category,$emp_num,$controller_name){
		$table_data = str_replace("~",'"',$table_data);
		$table_data = str_replace("`","'",$table_data);
		$table_data = str_replace("^","&",$table_data);
		$category_info   = $this->db->query("CALL sp_a_run ('SELECT','SELECT category_name FROM `cw_category` where trans_status = 1 and prime_category_id = $category')");
		$category_result = $category_info->result();
		$category_info->next_result();
		$category_name   = $category_result[0]->category_name;
		$category_name   = strtolower(str_replace(" ","_",$category_name));		
		$dompdf = new DOMPDF(array('enable_remote' => true,"enable_font_subsetting" => true));
		// Load HTML content 
		$dompdf->loadHtml($table_data);
		// (Optional) Setup the paper size and orientation
		$dompdf->setPaper('A4', 'portrait');
		// Render the HTML as PDF
		$dompdf->render();    
		// Output the generated PDF (1 = download and 0 = preview)
		$output 	= $dompdf->output();

		$folder     = $controller_name;
		$folder1    = $controller_name."_".$category_name;
		$pdf_name   = $emp_num;
		$final_html = $output;
		$oldmask = umask(0);
		if (!file_exists($folder)){
			mkdir($folder, 0777, true);
		}
		if (!file_exists($folder."/".$folder1)){
			mkdir($folder."/".$folder1, 0777, true);
		}
		//Check File Exist
		if(file_exists($folder."/".$folder1."/".$pdf_name.".pdf")){
			chmod($folder."/".$folder1."/".$pdf_name.".pdf", 0777);
			unlink($folder."/".$folder1."/".$pdf_name.".pdf");
		}
		file_put_contents($folder."/".$folder1."/".$pdf_name.".pdf" , $final_html);
		chmod($folder."/".$folder1."/".$pdf_name.".pdf", 0777);
		umask($oldmask);
		$path = $folder."/".$folder1."/".$pdf_name.".pdf";
		chmod($path, 0777, true);
		return $path;
	}
	
	//MRJ start 05OCT2020
	//formula column label name coloring
	public function coloring_label(){
		$formula_qry     = 'select * from cw_form_bind_input where input_cond_module_id = "'.$this->control_name.'" and trans_status = 1';
		$formula_data    = $this->db->query("CALL sp_a_run ('SELECT','$formula_qry')");
		$formula_result  = $formula_data->result();
		$formula_data->next_result();
		$this->formula_result = $formula_result;
	}
	
	public function role_based_condition(){
		$role_based_query  = 'select * from cw_role_base_condition where  role_module_id = "'.$this->control_name.'" and find_in_set("'.$this->logged_user_role.'",role_condition_for) and trans_status = 1';
		$role_based_info   = $this->db->query("CALL sp_a_run ('SELECT','$role_based_query')");
		$role_based_result = $role_based_info->result();
		$role_based_info->next_result();
		$role_based_condition = array();
		foreach($role_based_result as $key => $condition) {
			$role_based_condition[$condition->user_condition_type] = $condition->input_columns;
		}
		$this->role_based_condition = $role_based_condition;
	}
	public function trigger_sms($mobile_number,$sms_content,$template_id){
		//Get sms Configuration data
		$sms_config_query  = 'select sms_url,sms_sender_id,sms_username,sms_password,entityid from cw_company_information where trans_status = 1';
		$sms_config_info   = $this->db->query("CALL sp_a_run ('SELECT','$sms_config_query')");
		$sms_config_result = $sms_config_info->result();
		$sms_config_info->next_result();
		if($sms_config_result){
			$sms_url    = $sms_config_result[0]->sms_url;
			$sms_user   = $sms_config_result[0]->sms_username;
			$sms_pwd    = $sms_config_result[0]->sms_password;
			$sender_id  = $sms_config_result[0]->sms_sender_id;
			$entityid   = $sms_config_result[0]->entityid;
		}
		$url = "$sms_url?username=$sms_user&password=$sms_pwd&type=0&dlr=1&destination=$mobile_number&entityid=$entityid&source=$sender_id&message=".urlencode($sms_content)."&tempid=$template_id";
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		$output = curl_exec($ch);
		curl_close($ch);
		if($ch){
			return true;
		}		
	}
	public function load_sms_data($sms_design,$block_id,$view_id){
		$data['sms_sts'] 	= false;	
		$block_qry    		= 'select prime_sms_block_id,sms_block_column,sms_block_name,sms_block_table from cw_sms_block where sms_block_for = "'.$block_id.'" and trans_status = 1';
		$block_data   		= $this->db->query("CALL sp_a_run ('SELECT','$block_qry')");
		$block_result 		= $block_data->result();
		$block_data->next_result();
		$prime_sms_block_id  = $block_result[0]->prime_sms_block_id;
		$sms_block_column  	 = $block_result[0]->sms_block_column;
		$map_column			 = explode(",",$sms_block_column);

		$where_qry    = 'select where_condition from cw_sms_table_where where where_for_id = "'.$prime_sms_block_id.'" and trans_status = 1';
		$where_data   = $this->db->query("CALL sp_a_run ('SELECT','$where_qry')");
		$where_result = $where_data->result();
		$where_data->next_result();

		$form_qry     = 'select prime_module_id,prime_form_id,view_name,label_name,field_type,pick_list_type,pick_list,pick_table,auto_prime_id,auto_dispaly_value from cw_form_setting where trans_status = "1"';
		$form_data   = $this->db->query("CALL sp_a_run ('SELECT','$form_qry')");
		$form_result = $form_data->result_array();
		$form_data->next_result();
		$form_result = array_reduce($form_result, function($result, $arr){			
		    $result[$arr['prime_module_id']][$arr['label_name']][] = $arr;
		    return $result;
		}, array());

		$session_query      = 'select session_value from cw_session_value where session_for = 1 and trans_status = "1"';
		$session_data       = $this->db->query("CALL sp_a_run ('SELECT','$session_query')");
		$session_result     = $session_data->result();
		$session_data->next_result();

		$table_qry    = 'select line_prime_table,line_prime_col,line_join_type,line_join_table,line_join_col,line_sort from cw_sms_table where sms_table_for_id = "'.$prime_sms_block_id.'" and trans_status = 1';
		$table_data   = $this->db->query("CALL sp_a_run ('SELECT','$table_qry')");
		$table_result = $table_data->result();
		$table_data->next_result();

		foreach($block_result as $block){
			$sms_block_name      	= $block->sms_block_name;
			$sms_block_table     	= $block->sms_block_table;
			$sms_block_column    	= $block->sms_block_column;
			$line_table_query = "";
			foreach($table_result as $table){
				$line_prime_table      = $table->line_prime_table;
				$line_prime_col        = $table->line_prime_col;
				$line_join_type        = $table->line_join_type;
				$line_join_table       = $table->line_join_table;
				$line_join_col         = $table->line_join_col;
				$line_sort             = $table->line_sort;
				$module_name           = str_replace("cw_","",$line_prime_table);
				$prime_id              = "prime_".$module_name."_id";
				$join_module_name      = str_replace("cw_","",$line_join_table);
				$join_prime_id         = "prime_".$join_module_name."_id";
				if((int)$line_sort === 1){
					$line_prime_table = " $line_prime_table ";
					$line_join_table = " $line_join_table on $line_join_col = $line_prime_col ";
					$line_table_query .= " $line_prime_table  $line_join_type join $line_join_table"; 
				}else{
					$line_table_query .= " $line_join_type join $line_join_table on $line_join_col = $line_prime_col "; 
				}
			}
			if(!$line_table_query){
				$module_name      = str_replace("cw_","",$sms_block_table);
				$prime_id         = "prime_".$module_name."_id";
				$line_table_query = " $sms_block_table ";
			}
			if(!$sms_block_column){
				$sms_block_column = "*";
			}else{
				$select_query 	  = "";
				$pick_query       = "";
				foreach($map_column as $table_column){
					$map_column   = explode(".",$table_column);
					$table_name   = $map_column[0];
					$column 	  = $map_column[1];
					$control_name = str_replace('cw_',"",$table_name);
					$form_result_array = $form_result[$control_name][$column];
					foreach($form_result_array as $form){
						$prime_form_id  = (int)$form['prime_form_id'];
						$view_name      = $form['view_name'];
						$label_name     = $form['label_name'];
						$field_type     = (int)$form['field_type'];
						$pick_list_type = (int)$form['pick_list_type'];
						$pick_list      = $form['pick_list'];
						$pick_table     = $form['pick_table'];
						$auto_prime_id      = $form['auto_prime_id'];
						$auto_dispaly_value = $form['auto_dispaly_value'];
						if((int)$field_type === 4){
							$select_query .= 'DATE_FORMAT('.$table_name.'.'.$label_name.', "%d-%m-%Y") as '.$label_name.' , ';
						}else
						if(($field_type === 5) || ($field_type === 7)){
							if($pick_list_type === 1){
								$pick_list_val   = explode(",",$pick_list);
								$pick_list_val_1 = $pick_list_val[0];
								$pick_list_val_2 = $pick_list_val[1];
								
								$pick_query_as = $pick_table."_".$prime_form_id;
								$select_query .= "$pick_query_as.$pick_list_val_2 as $label_name , ";
								$pick_query .= " left join $pick_table as $pick_query_as on $pick_query_as.$pick_list_val_1 = $table_name.$label_name ";
							}else
							if($pick_list_type === 2){ 
								$pick_list_val_1 = $pick_table."_id";
								$pick_list_val_2 = $pick_table."_value";
								$pick_list_val_3 = $pick_table."_status";
								
								$pick_query_as = $pick_table."_".$prime_form_id;
								$select_query .= "$pick_query_as.$pick_list_val_2 as $label_name , ";
								$pick_query   .= " left join $pick_table as $pick_query_as on $pick_query_as.$pick_list_val_1 = $table_name.$label_name ";
							}
						}else
						if($field_type === 9){
							$pick_query_as = $pick_table."_".$prime_form_id;
							$select_query .= "$pick_query_as.$auto_dispaly_value as $label_name,";
							$pick_query .= " left join $pick_table as $pick_query_as on $pick_query_as.$auto_prime_id = $table_name.$label_name ";
						}else
						if(($field_type === 2) || ($field_type === 3)){
							$label_ytd  =	$label_name."_ytd";
							$select_query .= "$table_name.$label_name , ";
						}else{
							$select_query .= "$table_name.$label_name , ";
						}
					}					
				}
			}
			$where_trans = "";
			$where_trans_info = explode(",",$sms_block_table);
			foreach($where_trans_info as $trans_info){
				$where_trans .= "$trans_info.trans_status = 1 and ";
			}
			$where_trans = rtrim($where_trans,'and ');
			$where_condition = "";
			if($where_result){
				$where_condition = str_replace('^','"',$where_result[0]->where_condition);
				$where_condition = str_replace('@logged_id@',$this->logged_id,$where_condition);				
				$session_date_list  = array("logged_DMY"=>"d-m-Y","logged_YMD"=>"Y-m-d","logged_MY"=>"m-Y","logged_YM"=>"Y-m","logged_Y"=>"Y"); 
				foreach($session_result as $rslt){
					$session_value 	   = $rslt->session_value;
					if($session_value !== "access_data"){
						$exist_val = "@".$session_value."@";
						if($session_date_list[$session_value]){
							$date_formate      = $session_date_list[$session_value];
							$saved_session_val = date($date_formate);
						}else{
							$saved_session_val = $this->session->userdata($session_value);
						}
						$where_condition  = str_replace($exist_val,$saved_session_val,$where_condition);
					}
				}
			}
			$select_query = rtrim($select_query,',');
			$select_query = rtrim($select_query,' , ');

			$final_qry = "select $select_query from ".$line_table_query." $pick_query where $prime_id = ".$view_id." and  $where_trans $where_condition";
			$final_data   = $this->db->query("CALL sp_a_run ('SELECT','$final_qry')");
			$final_result = $final_data->result();
			$final_data->next_result();
			$count = 0;
			$assign_date_formate_list  = array("DMY"=>"d-m-Y","YMD"=>"Y-m-d","DFY"=>"d F Y","MY"=>"F-Y","YM"=>"Y-F","D"=>"d","M"=>"M","Y"=>"Y");
			$split_array = array();
			if($final_result){
				$data['sms_sts'] = true;
				foreach($final_result as $rslt){
					$count++;
					$map_column = explode(",",$sms_block_column);
					$td_line = "";
					foreach($map_column as $table_column){
						$map_column   = explode(".",$table_column);
						$column 	  = $map_column[1];
						$value        = $rslt->$column;
						$replace_val  = "@".$column."@";
						$sms_design = str_replace($replace_val,$value,$sms_design);
						foreach($assign_date_formate_list as $key=>$formate){
							$start         = "@".$key."_";
							$end           = "_".$key."@";
							$replace_val   = $start.$column.$end;
							$replace_val   = $start.$column.$end;
							$date_value    = date_create($value);
							$replace_value = date_format($date_value,$formate);
							$sms_design  = str_replace($replace_val,$replace_value,$sms_design);
						}
					}
				}
			}
		}
		$sms_design = str_replace("<br>","",$sms_design);
		$data['sms_design'] = $sms_design;
		return $data;
	}
	public function send_sms($insert_id,$pick_array,$previous_data,$mobile_list){
		$arraycompare 	   = array_diff_assoc($pick_array,$previous_data);
		$column 		   = http_build_query($arraycompare, '', '&');
		$column_qry = "";
		$mobile_no = "";
		if($column){
			$column 	   = str_replace('=','" and table_values = "',$column);
			$column 	   = str_replace('&','" or query_list_id = "',$column);
			$column_qry	   = 'query_list_id = "'.$column.'"';
			$design_qry    = 'select sms_design,prime_sms_info_id,template_id,mobile_no_column,employee_column,notify_tl,notify_manager from cw_sms_design inner join cw_sms_info on cw_sms_info.prime_sms_info_id=cw_sms_design.sms_design_for where cw_sms_info.sms_info_module_id = "'.$this->control_name.'" and '.$column_qry.' and cw_sms_info.trans_status = 1';
			$design_data   		= $this->db->query("CALL sp_a_run ('SELECT','$design_qry')");
			$design_result		= $design_data->result();
			$design_data->next_result();

			$sms_design    		= $design_result[0]->sms_design;
			$block_id     		= $design_result[0]->prime_sms_info_id;
			$template_id     	= $design_result[0]->template_id;
			$mobile_no_column   = $design_result[0]->mobile_no_column;
			$employee_column    = $design_result[0]->employee_column;
			$employee_column 	= $pick_array[$employee_column];

			if($mobile_list){
				$mobile_no 		= $pick_array[$mobile_no_column];
			}else{
				$employee_qry       = 'select employee_code,tl_report,manager_report,'.$mobile_no_column.' from cw_employees where cw_employees.employee_code = "'.$employee_column.'" and cw_employees.trans_status = 1';
				$employee_info      = $this->db->query("CALL sp_a_run ('SELECT','$employee_qry')");
				$employee_result    = $employee_info->result();
				$employee_info->next_result();
				$mobile_no 			= $employee_result[0]->$mobile_no_column;
			}
			if($mobile_no && $template_id && $sms_design){
				$sms_design    = $this->load_sms_data($sms_design,$block_id,$insert_id);
				$sms_content   = $sms_design['sms_design'];
				if($sms_content){
					$sms_rlst 	   = $this->trigger_sms($mobile_no,$sms_content,$template_id);
				}
				if($sms_rlst){
					$sms_status = 1;
					$sms_msg    = " and Sms Sent";
					$msg_rslt   = array('sms_status'=>$sms_status,'sms_msg'=>$sms_msg);
				}else{
					$sms_status = 0;
					$sms_msg    = " and Sms not Sent";
					$msg_rslt   = array('sms_status'=>$sms_status,'sms_msg'=>$sms_msg);
				}
				return $msg_rslt;
			}else{
				$sms_status = 0;
				$sms_msg    = "Mobile No or Tempate id or Sms Content Not Available";
				$msg_rslt   = array('sms_status'=>$sms_status,'sms_msg'=>$sms_msg);
				return $msg_rslt;
			}
		}else{
			$sms_status = 0;
			$sms_msg    = "Picklist Not changed";
			$msg_rslt   = array('sms_status'=>$sms_status,'sms_msg'=>$sms_msg);
			return $msg_rslt;
		}
	}
	
	public function send_mail_dynamic($mail_status_name,$get_to_mail,$config_result,$email_subject,$email_design,$bcc_mail,$attachment,$bcc_email_column){ 
		$smtp_server   = $config_result[0]->smtp_server;
		$sender_name   = $config_result[0]->sender_name;
		//$bcc           = explode(",",$config_result[0]->bcc);
		$port_no       = $config_result[0]->port_no;
		$sender_email  = $config_result[0]->sender_email;
		$username      = $config_result[0]->mail_username;
		$password      = $config_result[0]->mail_password;
		$conn_type     = $config_result[0]->connection_type;
		if($get_to_mail){
			try{
				$mail = new PHPMailer();
				// $mail->SMTPDebug = 1;
				$mail->IsSMTP();
				$mail->Host 	   = $smtp_server; // Your SMTP PArameter
				$mail->Port 	   = $port_no; // Your Outgoing Port
				$mail->SMTPAuth    = ($conn_type === "") ? false : true; // This Must Be True
				$mail->Username    = $username; // Your Email Address
				$mail->Password    = $password; // Your Password
				$mail->SMTPSecure  = ($conn_type === "") ? false : true; // Check Your Server's Connections for TLS or  SSL
				$mail->SMTPAutoTLS = ($conn_type === "") ? false : true;	
				$mail->From        = $sender_email;
				$mail->FromName    = $sender_name;

				$mail_arr       = explode(",",$get_to_mail);
				if((int)count($mail_arr ?? []) > 1){
					foreach ($mail_arr as $mail_key => $to_mail){
						$mail->AddAddress($to_mail);
					}
				}else{
					$mail->AddAddress($get_to_mail);
				}
				$bcc_mail           = explode(",",$bcc_mail);
				if((int)count($bcc_mail ?? []) > 0){
					foreach ($bcc_mail as $bcc_key => $bcc_mails){
						if($bcc_mails){
							$mail->AddCC($bcc_mails);
						}						
					}
				}
				$bcc_email_column           = explode(",",$bcc_email_column);
				if((int)count($bcc_email_column ?? []) > 0){
					foreach ($bcc_email_column as $bccs_key => $bccs_mails){
						if($bccs_mails){
							$mail->AddCC($bccs_mails);
						}						
					}
				}
				if(file_exists($attachment)){
					$mail->addAttachment($attachment);	
				}
				//$mail->Debugoutput = 'html';
				$mail->IsHTML(true);
				$mail->Subject = $email_subject;
				$mail->Body    = $email_design;
				if($mail->Send()){
					$status = 1;
					$msg = $mail_status_name." Mail Sent Successfully,";
				}else{
					$status = 0;
					$msg = $mail_status_name." Mail Not Sent,";
					echo 'Mailer error: ' . $mail->ErrorInfo;
				}	
				//Attachment
			}catch(phpmailerException $e){
				$status = 0;
				$msg = $mail_status_name." Mail Not Sent,";
			}catch(Exception $e){
				$status = 0;
				$msg = $mail_status_name." Mail Not Sent,";
			}
		}else{
			$msg = $mail_status_name." Mail Id Not Available,";
		}
		return $msg;
	}
	public function get_email_attachment($attachment,$email_subject,$pdf_name){
		$style  = "<style>
			table{
				border: 1px !important;
				border-collapse: collapse !important;
				empty-cells: show !important;
				max-width: 100% !important;
				font-size: 13px !important;
			}
			tbody {
				border: 1px !important;
				border-collapse: collapse !important; 
				empty-cells: show !important;
				max-width: 100% !important;
				font-size: 13px !important;
			}
			td, th {
				border: 1px solid #000 !important;
				font-size: 13px !important;
			}
			td.fr-thick,th.fr-thick {
				border-width: 2px !important;
			}
			table.fr-dashed-borders td, table.fr-dashed-borders th {
				border-style: dashed !important;
			}
		</style>";
		$attachment  = $style."".$attachment;
		$table_data = "<!DOCTYPE html><html> <body>".$attachment."</body></html>";
		// Load pdf library
        // $this->load->library('pdf');
		// 	// Load HTML content 
		// $this->dompdf->loadHtml($table_data);
		// 	// Render the HTML as PDF
		// $this->dompdf->render();
		// 	// Output the generated PDF (1 = download and 0 = preview)
		// $output 	   = $this->dompdf->output();
		$dompdf = new DOMPDF(array('enable_remote' => true,"enable_font_subsetting" => true));
		// Load HTML content 
		$dompdf->loadHtml($table_data);
		// Render the HTML as PDF
		$dompdf->render();    
		// Output the generated PDF (1 = download and 0 = preview)
		$output 	= $dompdf->output();
		$conroler_name = $this->control_name;
		$pdf_name 	   = str_replace(' ', '_', $pdf_name);
		//new permission changes
		$folder        = $conroler_name."/".$pdf_name;
		$final_html    = $output;
		$oldmask       = umask(0);
		if(!file_exists($folder)){
			mkdir($folder, 0777, true);
		}
		if(!file_exists($conroler_name."/".$pdf_name)){
			mkdir($conroler_name."/".$pdf_name, 0777, true);
		}
		//Check File Exist
		if(file_exists($conroler_name."/".$pdf_name.".pdf")){
			chmod($conroler_name."/".$pdf_name.".pdf", 0777);
			unlink($conroler_name."/".$pdf_name.".pdf");
		}
		file_put_contents($conroler_name."/".$pdf_name.".pdf" , $final_html);
		chmod($conroler_name."/".$pdf_name.".pdf", 0777);
		umask($oldmask);
		$path = $conroler_name."/".$pdf_name.".pdf";
		chmod($path, 0777);
		return $path;
	}
	//Check Email Enable Count
	public function get_email_setting(){
		$email_setting_qry    = 'select count(*) as email_count from cw_modules where cw_modules.module_id = "'.$this->control_name.'" and cw_modules.email_setting = 1 and cw_modules.trans_status = 1';
		$email_setting_info   = $this->db->query("CALL sp_a_run ('SELECT','$email_setting_qry')");
		$email_setting_result = $email_setting_info->result();
		$email_setting_info->next_result();
		$email_count 		  = $email_setting_result[0]->email_count;
		$this->email_count 	  = $email_count;
	}
	/* Dynamic mail End - Latha*/

	public function load_email_data($email_doc_id,$view_id){
		$data['print_sts']    = false;
		$design_qry           = 'select email_design,print_type,email_design_for from cw_email_design inner join cw_print_info on cw_print_info.prime_print_info_id=cw_email_design.email_design_for where print_type = "'.$email_doc_id.'" and cw_print_info.trans_status = 1';
		$design_data          = $this->db->query("CALL sp_a_run ('SELECT','$design_qry')");
		$design_result        = $design_data->result();
		$design_data->next_result();
		$print_design         = $design_result[0]->email_design;
		$print_type           = $design_result[0]->print_type;
		$email_design_for     = $design_result[0]->email_design_for;
		$style  = "<style>
		table{
			border: 1px !important;
			border-collapse: collapse !important;
			empty-cells: show !important;
			max-width: 100% !important;
			font-size: 13px !important;
		}
		tbody {
			border: 1px !important;
			border-collapse: collapse !important; 
			empty-cells: show !important;
			max-width: 100% !important;
			font-size: 13px !important;
		}
		td, th {
			border: 1px solid #000 !important;
			font-size: 13px !important;
		}
		td.fr-thick,th.fr-thick {
			border-width: 2px !important;
		}
		table.fr-dashed-borders td, table.fr-dashed-borders th {
			border-style: dashed !important;
		}
		</style>";
		$print_design  = $style."".$print_design;
		$print_design  = str_replace('~','"',$print_design);
		$block_qry    = 'select * from cw_print_block where print_block_for = "'.$email_design_for.'" and trans_status = 1';
		$block_data   = $this->db->query("CALL sp_a_run ('SELECT','$block_qry')");
		$block_result = $block_data->result();
		$block_data->next_result();
		foreach($block_result as $block){
			$prime_print_block_id  = $block->prime_print_block_id;
			$print_block_name      = $block->print_block_name;
			$print_block_type      = (int)$block->print_block_type;
			$print_block_table     = $block->print_block_table;
			$print_block_column    = $block->print_block_column;
			$suppressed_data       = $block->suppressed_data;
			$cumulative_data       = $block->cumulative_data;

			$table_qry    = 'select * from cw_print_table where print_table_for_id = "'.$prime_print_block_id.'" and trans_status = 1';
			$table_data   = $this->db->query("CALL sp_a_run ('SELECT','$table_qry')");
			$table_result = $table_data->result();
			$table_data->next_result();
			$line_table_query = "";
			$cutome_table_check = array('transactions'=>'cw_transactions');
			foreach($table_result as $table){
				$line_prime_table      = $table->line_prime_table;
				$line_prime_col        = $table->line_prime_col;
				$line_join_type        = $table->line_join_type;
				$line_join_table       = $table->line_join_table;
				$line_join_col         = $table->line_join_col;
				$line_sort             = $table->line_sort;
				$module_name           = str_replace("cw_","",$line_prime_table);
				$prime_id              = "prime_".$module_name."_id";
				$join_module_name      = str_replace("cw_","",$line_join_table);
				$join_prime_id         = "prime_".$join_module_name."_id";
				if((int)$line_sort === 1){
					if($cutome_table_check[$module_name]){
						$line_prime_table = " $line_prime_table ";
					}else{
						$line_prime_table = " $line_prime_table ";
					}
					if($cutome_table_check[$join_module_name]){
						$line_join_table = " $line_join_table on $line_join_col = $line_prime_col";
					}else{
						$line_join_table = " $line_join_table on $line_join_col = $line_prime_col ";
					}
					$line_table_query .= " $line_prime_table  $line_join_type join $line_join_table"; 
				}else{
					if($cutome_table_check[$join_module_name]){
						$line_table_query .= " $line_join_type join $line_join_table on $line_join_col = $line_prime_col "; 
					}else{
						$line_table_query .= " $line_join_type join $line_join_table on $line_join_col = $line_prime_col "; 
					}
				}
			}
			if(!$line_table_query){
				$module_name      = str_replace("cw_","",$print_block_table);
				$prime_id         = "prime_".$module_name."_id";
				$line_table_query = " $print_block_table ";
			}

			if(!$print_block_column){
				$print_block_column = "*";
			}else{
				$select_query = "";
				$select_ytd_query = "";
				$pick_query   = "";
				$map_column = explode(",",$print_block_column);
				foreach($map_column as $table_column){
					$map_column   = explode(".",$table_column);
					$table_name   = $map_column[0];
					$column 	  = $map_column[1];
					$control_name = str_replace('cw_',"",$table_name);
					if($control_name === "transactions"){
						$control_name = "employees";
					}
					$form_qry    = 'select prime_form_id,view_name,label_name,field_type,pick_list_type,pick_list,pick_table,auto_prime_id,auto_dispaly_value from cw_form_setting where prime_module_id = "'.$control_name.'" and  label_name = "'.$column.'"  and trans_status = "1"';
					$form_data   = $this->db->query("CALL sp_a_run ('SELECT','$form_qry')");
					$form_result = $form_data->result();
					$form_data->next_result();
					foreach($form_result as $form){
						$prime_form_id  = (int)$form->prime_form_id;
						$view_name      = $form->view_name;
						$label_name     = $form->label_name;
						$field_type     = (int)$form->field_type;
						$pick_list_type = (int)$form->pick_list_type;
						$pick_list      = $form->pick_list;
						$pick_table     = $form->pick_table;
						$auto_prime_id      = $form->auto_prime_id;
						$auto_dispaly_value = $form->auto_dispaly_value;
						if((int)$field_type === 4){
							$select_query .= 'DATE_FORMAT('.$table_name.'.'.$label_name.', "%d-%m-%Y") as '.$label_name.' , ';
						}else
						if(($field_type === 5) || ($field_type === 7)){
							if($pick_list_type === 1){
								$pick_list_val   = explode(",",$pick_list);
								$pick_list_val_1 = $pick_list_val[0];
								$pick_list_val_2 = $pick_list_val[1];
								
								$pick_query_as = $pick_table."_".$prime_form_id;
								$select_query .= "$pick_query_as.$pick_list_val_2 as $label_name , ";
								$pick_query .= " left join $pick_table as $pick_query_as on $pick_query_as.$pick_list_val_1 = $table_name.$label_name ";
							}else
							if($pick_list_type === 2){ 
								$pick_list_val_1 = $pick_table."_id";
								$pick_list_val_2 = $pick_table."_value";
								$pick_list_val_3 = $pick_table."_status";
								
								$pick_query_as = $pick_table."_".$prime_form_id;
								$select_query .= "$pick_query_as.$pick_list_val_2 as $label_name , ";
								$pick_query   .= " left join $pick_table as $pick_query_as on $pick_query_as.$pick_list_val_1 = $table_name.$label_name ";
							}
						}else
						if($field_type === 9){
							$pick_query_as = $pick_table."_".$prime_form_id;
							$select_query .= "$pick_query_as.$auto_dispaly_value as $label_name,";
							$pick_query .= " left join $pick_table as $pick_query_as on $pick_query_as.$auto_prime_id = $table_name.$label_name ";
						}else
						if(($field_type === 2) || ($field_type === 3)){
							$label_ytd  =	$label_name."_ytd";
							$select_ytd_query .= "sum($table_name.$label_name) as $label_ytd, ";
							$select_query .= "$table_name.$label_name , ";
						}else{
							$select_query .= "$table_name.$label_name , ";
						}
					}					
				}
			}
			$where_trans = "";
			$where_trans_info = explode(",",$print_block_table);
			foreach($where_trans_info as $trans_info){
				if($trans_info === "cw_transactions"){
					$select_query .= "cw_transactions.transactions_month , ";
				}				
				$where_trans .= "$trans_info.trans_status = 1 and ";
			}
			$where_trans = rtrim($where_trans,'and ');
			$where_qry    = 'select * from cw_print_table_where where where_for_id = "'.$prime_print_block_id.'" and trans_status = 1';
			$where_data   = $this->db->query("CALL sp_a_run ('SELECT','$where_qry')");
			$where_result = $where_data->result();
			$where_data->next_result();
			$where_condition = "";
			if($where_result){
				$where_condition = str_replace('^','"',$where_result[0]->where_condition);
				$where_condition = str_replace('@logged_id@',$this->logged_id,$where_condition);				
				$session_date_list  = array("logged_DMY"=>"d-m-Y","logged_YMD"=>"Y-m-d","logged_MY"=>"m-Y","logged_YM"=>"Y-m","logged_Y"=>"Y"); 
				$session_query      = 'select session_value from cw_session_value where session_for = 1 and trans_status = "1"';
				$session_data       = $this->db->query("CALL sp_a_run ('SELECT','$session_query')");
				$session_result     = $session_data->result();
				$session_data->next_result();
				foreach($session_result as $rslt){
					$session_value 	   = $rslt->session_value;
					if($session_value !== "access_data"){
						$exist_val = "@".$session_value."@";
						if($session_date_list[$session_value]){
							$date_formate      = $session_date_list[$session_value];
							$saved_session_val = date($date_formate);
						}else{
							$saved_session_val = $this->session->userdata($session_value);
						}
						$where_condition  = str_replace($exist_val,$saved_session_val,$where_condition);
					}
				}
			}
			$select_query = rtrim($select_query,',');
			$select_query = rtrim($select_query,' , ');
			if((int)$cumulative_data === 1){
				$start_fin_date = $this->financial_info[0]->start_date;
				$start_fin_date = date('m-Y',strtotime($start_fin_date));
				$end_fin_date   = $this->financial_info[0]->end_date;
				$end_fin_date   = date('m-Y',strtotime($end_fin_date));
				$select_ytd_query = rtrim($select_ytd_query,',');
				$select_ytd_query = rtrim($select_ytd_query,' , ');
				$where_ytd_condition  = ' and date_format(str_to_date(transactions_month, "%m-%Y") , "%Y-%m")  >= date_format(str_to_date("'.$start_fin_date.'", "%m-%Y"), "%Y-%m") and date_format(str_to_date(transactions_month, "%m-%Y") , "%Y-%m")  <= date_format(str_to_date("'.$end_fin_date.'", "%m-%Y"), "%Y-%m")';
				$final_ytd_qry = "select $select_ytd_query from $line_table_query $pick_query  where $where_trans $where_condition  $where_ytd_condition";
				$final_ytd_data   = $this->db->query("CALL sp_a_run ('SELECT','$final_ytd_qry')");
				$final_ytd_result = $final_ytd_data->result();
				$final_ytd_data->next_result();
				foreach($final_ytd_result as $ytd_rslt){
					$map_column = explode(",",$print_block_column);
					foreach($map_column as $table_column){
						$map_column   = explode(".",$table_column);
						$ytd_column 	  = $map_column[1]."_ytd";
						$ytd_value        = $ytd_rslt->$ytd_column;
						$replace_ytd_val  = "@".$ytd_column."@";
						$print_design  = str_replace($replace_ytd_val,$ytd_value,$print_design);
					}
				}
			}
			$final_qry = "select $select_query from ".$line_table_query." $pick_query where $prime_id = ".$view_id." and  $where_trans $where_condition";
			$final_data   = $this->db->query("CALL sp_a_run ('SELECT','$final_qry')");
			$final_result = $final_data->result();
			$final_data->next_result();
			$tr_line = "";
			$th_line = "";
			$count = 0;
			$assign_date_formate_list  = array("DMY"=>"d-m-Y","YMD"=>"Y-m-d","DFY"=>"d F Y","MY"=>"F-Y","YM"=>"Y-F","D"=>"d","M"=>"M","Y"=>"Y");
			$split_qry    = 'select * from cw_print_split where trans_status = 1 and split_table_info ="'.$print_doc_id.'"';
			$split_data   = $this->db->query("CALL sp_a_run ('SELECT','$split_qry')");
			$split_result = $split_data->result();
			$split_data->next_result();
			$split_array = array();
			foreach($split_result as $split){
				$split_info  = $split->split_info;
				$split_colum = $split->split_colum;
				$split_array[$split_colum] = $split_info;
			}		
			if($final_result){
				$data['print_sts'] = true;
				foreach($final_result as $rslt){
					$count++;
					$map_column = explode(",",$print_block_column);
					$td_line = "";
					foreach($map_column as $table_column){
						$map_column   = explode(".",$table_column);
						$column 	  = $map_column[1];
						$value        = $rslt->$column;
						$replace_val  = "@".$column."@";
						//amount number is changed to in words for net pays--07SEP2019
						if($column == 'employee_code'){
							$value         = $rslt->$column;
							$print_design  = str_replace($replace_val,$value,$print_design);
							//DR CODE START *
							$application_url = site_url();
							$application_link = "<a href='$application_url'> Application Link </a>";
							$print_design  = str_replace("@application_link@",$application_link,$print_design);
							//FOR APPROVE LEAVE REQUEST
							$app_url       = $application_url.'/app/api_controller.php';
							$approve_link  = "<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
							<!DOCTYPE html>
							  <button class='btn btn-primary btn-sm' id= 'approve' onclick = 'approve()'>Approve</button>
							</html>
							<script>
								function approve(){
									alert();
									var send_url = '$app_url'; 
									$.ajax({
										type: 'POST',
										url: send_url,
										data:{frm:approve,view_id:$view_id},
										success: function(data) {
											console.log(data);
										}
									});
								}
							</script>";
							$print_design  = str_replace("@approve@",$approve_link,$print_design);
							//FOR REJECT LEAVE REQUEST
							$reject_link  = "<form>
											  <button class='btn btn-primary btn-sm' id= 'reject' onclick = 'reject()'>Reject</button>
											</form>
											<script>
												function reject(){
													var send_url = '$app_url'; 
													$.ajax({
														type: 'POST',
														url: send_url,
														data:{frm:reject,view_id:$view_id},
														success: function(data) {
													
														}
													});
												}
											</script>";
							$print_design  = str_replace("@reject@",$reject_link,$print_design);
							//DR CODE END *

						}else
						if($column == 'net_pay'){
							$value         = $rslt->$column;
							$print_design  = str_replace($replace_val,$value,$print_design);
							$net_pay_val   = $value;
							$net_pay_words = $this->numbertowords($net_pay_val);
							$net_pay_words = strtoupper($net_pay_words);
							$print_design  = str_replace("@net_pay_words@",$net_pay_words,$print_design);
						}else
						if($column == 'employee_name'){
							$value         = ucwords($rslt->$column);
							$print_design  = str_replace($replace_val,$value,$print_design);
						}else
						if($column == 'reporting_person'){
							$value         = ucwords($rslt->$column);
							$print_design  = str_replace($replace_val,$value,$print_design);
						}else
						if($column == 'salary'){
							$value         = $rslt->$column;
							$print_design  = str_replace($replace_val,$value,$print_design);
							$salary_val   = $value;
							$salary_words = $this->numbertowords($salary_val);
							$salary_words = ucwords($salary_words);
							$print_design  = str_replace("@salary_words@",$salary_words,$print_design);
						}
						
						if($split_array[$replace_val]){
							//Process split informtion 
							$process_function = $split_array[$replace_val];
							if((int)$process_function === 1){
								$transactions_month = $final_result[0]->transactions_month;
								$employee_code      = $final_result[0]->employee_code;
								$loan_info = $this->get_loan_value($transactions_month,$employee_code);
								$print_design = str_replace($replace_val,$loan_info,$print_design);
							}
						}else{
							if($print_block_type === 1){
								$print_design = str_replace($replace_val,$value,$print_design);
								foreach($assign_date_formate_list as $key=>$val){
									if($column == 'transactions_month'){//transactions month static updated
										$start         = "@".$key."_";
										$end           = "_".$key."@";
										$replace_val   = $start.$column.$end;
										$value         = date('Y-m-d',strtotime("01-".$rslt->$column));
										$date_value    = date_create($value);
										$replace_value = strtoupper(date_format($date_value,$val));
										$print_design  = str_replace($replace_val,$replace_value,$print_design);
									}else{//not static month updated
										$start         = "@".$key."_";
										$end           = "_".$key."@";
										$replace_val   = $start.$column.$end;
										$replace_val   = $start.$column.$end;
										$date_value    = date_create($value);
										if($date_value){
											$replace_value = date_format($date_value,$val);
											$print_design  = str_replace($replace_val,$replace_value,$print_design);
										}
									}
								}
							}else
							if($print_block_type === 2){
								$td_line .= "<td style='text-align:center;'>$value</td>";
							}
							if($count === 1){
								$head_name = ucwords(str_replace("_"," ",$column));
								$th_line .= "<th style='text-align:center;'>$head_name</th>";
							}
						}
					}
					if($print_block_type === 2){
						if($count === 1){
							$th_line  = "$th_line";
						}
						$tr_line .= "<tr>$td_line</tr>";
					}
				}
				if($print_block_type === 2){
					$table_list  = "<table style='width:100%;'><thead>$th_line</thead><tbody>$tr_line</tbody></table>";
					$replce_block = "@".strtolower(str_replace(" ","_",$print_block_name))."@";
					$print_design = str_replace($replce_block,$table_list,$print_design);
				}
			}
			$data['suppressed_data'] = $suppressed_data;
		}
		// $print_design = str_replace("<br>","",$print_design);
		$data['print_design'] = $print_design;
		return $data;
	}
	public function send_email_notification($to_email,$first_to_email,$second_to_email,$bcc_mails,$email_subject,$body_content,$email_attachment){
		if($to_email){
			$config_query  = 'SELECT smtp_server,sender_name,bcc,port_no,sender_email,mail_username,mail_password,connection_type FROM cw_mail_configurations WHERE trans_status = 1';
			$config_info   = $this->db->query("CALL sp_a_run ('SELECT','$config_query')");
			$config_result = $config_info->result();
			$config_info->next_result();
			$smtp_server   = $config_result[0]->smtp_server;
			$sender_name   = $config_result[0]->sender_name;
			//$bcc           = explode(",",$config_result[0]->bcc);
			$port_no       = $config_result[0]->port_no;
			$sender_email  = $config_result[0]->sender_email;
			$username      = $config_result[0]->mail_username;
			$password      = $config_result[0]->mail_password;
			$conn_type     = $config_result[0]->connection_type;
			try{
				$mail = new PHPMailer();
				//$mail->SMTPDebug = 3; 
				// $mail->SMTPAuth = true; // This Must Be True
				// $mail->Username = $username; // Your Email Address
				// $mail->Password = $password; // Your Password
				// $mail->SMTPSecure = $conn_type; // Check Your Server's Connections for TLS or SSL
				
				$mail->IsSMTP();
				$mail->Host 	   = $smtp_server; // Your SMTP PArameter
				$mail->Port 	   = $port_no; // Your Outgoing Port
				$mail->SMTPAuth    = ($conn_type === "") ? false : true; // This Must Be True
				$mail->Username    = $username; // Your Email Address
				$mail->Password    = $password; // Your Password
				$mail->SMTPSecure  = ($conn_type === "") ? false : true; // Check Your Server's Connections for TLS or  SSL
				$mail->SMTPAutoTLS = ($conn_type === "") ? false : true;
				$mail->From        = $sender_email;
				$mail->FromName    = $sender_name;

				if($to_email){
					$mail->AddAddress($to_email);
				}
				if($first_to_email){		
					$mail->AddAddress($first_to_email);
				}
				if($second_to_email){		
					$mail->AddAddress($second_to_email);
				}
				if($bcc_mails ?? []){
					foreach ($bcc_mails as $key => $mail_bcc){
						$mail->AddCC($mail_bcc);
					}
				}
				$mail->IsHTML(true);
				$mail->Subject = $email_subject;
				$mail->Body    = $body_content;
				//Attachment
				$folder = $email_attachment;
				if($folder){
					if(file_exists($folder)){
						$mail= $mail->Send();
						if($mail){
							$status = 1;
						}			
					}else{
						$status = 0;
					}
				}else{
					$mail= $mail->Send();
					if($mail){				
						$status = 1;
					}else{
						$status = 0;
					}
				}
			}catch(phpmailerException $e){
				$status = 0;
				$return_values = array('success'=>false,'message'=>"Mail Not Sent");
				return false;
			}catch(Exception $e){
				$status = 0;
				$return_values = array('success'=>false,'message'=>"Mail Not Sent");
				return false;
			}
			if($status){
				
				$return_values = array('success'=>true,'message'=>"Mail Successfully Sent");
				return $return_values;
			}else{
				$return_values = array('success'=>false,'message'=>"Mail Not Sent");
				return false;
			}
		}else{
			$return_values = array('success'=>false,'message'=>"Please Add Employee email id and Try Again!!");
			return $return_values;
		}
	}

	// PROVIDE TABLE VIEW
	public function get_table_info(){
		$table_query = 'select label_name,view_name,field_type from cw_form_setting  where prime_module_id = "'.$this->control_name.'" and input_view_type IN (1,2) and table_show = "1" ORDER BY table_sort asc';
	//and FIND_IN_SET("'.$this->logged_role.'",field_for) Removed for show all inputs
		$table_info = $this->db->query("CALL sp_a_run ('SELECT','$table_query')");
		$result   = $table_info->result();
		$table_info->next_result();
		$this->table_info = $result;
	}
	public function common_generate_pdf($table_data,$folder,$file_name,$set_paper,$paper_size,$pdf_set_password,$password){
		$table_data = str_replace("~",'"',$table_data);
		$table_data = str_replace("`","'",$table_data);
		$table_data = str_replace("^","&",$table_data);
		// Load pdf library
		$pdf = new DOMPDF(array('enable_remote' => true,"enable_font_subsetting" => true));
		// Load HTML content 
		$pdf->loadHtml($table_data);
		// (Optional) Setup the paper size and orientation
		$pdf->setPaper($paper_size, $set_paper);
		// Render the HTML as PDF
		$pdf->render();
		//define('DOMPDF_ENABLE_AUTOLOAD', false);
		if($pdf_set_password === "1"){
			//SET Production
			$pdf->get_canvas()->get_cpdf()->setEncryption($password, $password);
		}        
		// Output the generated PDF (1 = download and 0 = preview)
		$output 	= $pdf->output();
		$final_html = $output;
		$oldmask 	= umask(0);
		if (!file_exists($folder)){
			mkdir($folder, 0755, true);
		}
		//File write
		file_put_contents($folder."/".$file_name.".pdf" , $final_html);
		chmod($folder."/".$file_name.".pdf", 0755);
		umask($oldmask);
		$path = $folder."/".$file_name.".pdf";
		
		return $path;
	}
	// EXPRIENCE YEAR CALCULATE
	public function years_calculate($date_of_join,$last_work_date){
		$date_of_join     = date('Y-m-d H:i:s',strtotime($date_of_join));
		$last_work_date   = date('Y-m-d H:i:s',strtotime($last_work_date));
		$date_of_join 	  = new DateTime($date_of_join);
		$last_work_date   = new DateTime($last_work_date);
		$interval 		  = $date_of_join->diff($last_work_date);
		$total_experience = $interval->format('%y Years %m Month');
		return $total_experience;
	}
	public function company_info(){
		$company_qry  = 'select * from cw_company_information where cw_company_information.trans_status = 1';
		$comp_info    = $this->db->query("CALL sp_a_run ('SELECT','$company_qry')");
		$comp_result  = $comp_info->result();
		$comp_info->next_result();
		$this->company_info = $comp_result;
		return $comp_result;
	}
	//PROCESS MONTH SET FOR IMPORT PROCESS 
	public function process_month_set(){
		$category              = $this->input->post('category');
		//GET DEFAULT FINANCIAL YEAR
		$financial_info        = $this->get_leave_financial_details();
		$prime_financial_id    = $financial_info[0]->prime_leave_financial_year_id;	
		$starting_date         = date('Y-m-d',strtotime($financial_info[0]->starting_date));	
		$ending_date           = date('Y-m-d',strtotime($financial_info[0]->ending_date));
		//GET A EMPLOYEE CODE AND PROCESS MONTH FORM LEAVE EXPORT MODULE
		$payroll_posting_query  = 'SELECT role as category,date_format(MAX(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y")) , "%m-%Y") AS process_month from cw_transactions where cw_transactions.role ="'.$category.'" and cw_transactions.trans_status = 1';			
		$payroll_posting_info   = $this->db->query("CALL sp_a_run ('SELECT','$payroll_posting_query')");
        $payroll_posting_result = $payroll_posting_info->result();
        $payroll_posting_info->next_result();
        $process_month          =  $payroll_posting_result[0]->process_month;
        if(!$process_month){
	    	$process_month = date("m-Y",strtotime($starting_date));
	    }else{
	    	$process_month = date("m-Y",strtotime("+1 month",strtotime("01-".$process_month)));
	    }
	    echo json_encode(array('process_month' =>$process_month));
	}
	//if we changes a shift request then we process a time entry 
	public function time_entry_process($employee_code,$shift_date,$shift_name){
		$time_entry_qry      = 'select COUNT(*) as time_entry_count from cw_time_entry where cw_time_entry.employee_code = "'.$employee_code.'" and cw_time_entry.att_date = "'.$shift_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();
		$time_entry_info->next_result();
		$time_entry_count    = (int)$time_entry_result[0]->time_entry_count;
		if($time_entry_count){
			$time_entry_run_info  = $this->db->query("CALL itsp_prcatt ('$shift_date','$shift_date','$employee_code')");
			$time_entry_run_rslt  = $time_entry_run_info->result();
			$time_entry_run_info->next_result();
			if($time_entry_run_rslt){
				return true;
			}else{
				return false;
			}
		}else{
			return true;
		}
	}
	//SHIFT CHANGE REQUEST CHECK FOR PERMISSION AND MANUAL PUNCH AND BUSINES TRIP
	public function check_exist_shift_sts($component_value,$employee_code,$shift_date,$rkey){
		$leave_financial_info = $this->get_leave_financial_details();
		$financial_year_id    = $leave_financial_info[0]->prime_leave_financial_year_id;	

		//CHECK PENDING SHIFT CHANGE EXIST FROM REQUEST
		if($rkey === "pastAtt"){
			$shift_request_qry    = 'SELECT count(cw_past_attendance_request.prime_past_attendance_request_id) as count FROM cw_past_attendance_request WHERE cw_past_attendance_request.employee_code = "'.$employee_code.'" and cw_past_attendance_request.shift_date = "'.$shift_date.'" and cw_past_attendance_request.request_type = "6" and cw_past_attendance_request.leave_status in (1) and cw_past_attendance_request.financial_setting_id = "'.$financial_year_id.'" and cw_past_attendance_request.trans_status = 1';
		}else{
			$shift_request_qry    = 'SELECT count(cw_request.prime_request_id) as count FROM cw_request WHERE cw_request.employee_code = "'.$employee_code.'" and cw_request.shift_date = "'.$shift_date.'" and cw_request.request_type = "6" and cw_request.leave_status in (1) and cw_request.financial_setting_id = "'.$financial_year_id.'" and cw_request.trans_status = 1';
		}


		// cw_request.leave_status in (1,2)
		$shift_request_info   = $this->db->query("CALL sp_a_run ('SELECT','$shift_request_qry')");
		$shift_request_rslt   = $shift_request_info->result();
		$shift_request_info->next_result();	
		$shift_count          = (int)$shift_request_rslt[0]->count;

		if($shift_count){
			return false;
		}else{
			//Check Exist from Leave Entry 
			/*$leave_entry_qry  = 'SELECT count(cw_leave_entry.prime_leave_entry_id) as count FROM cw_leave_entry WHERE cw_leave_entry.employee_code = "'.$employee_code.'" and cw_leave_entry.leave_date = "'.$shift_date.'" and cw_leave_entry.leave_status in (1,2) and cw_leave_entry.date_type in (1) and cw_leave_entry.financial_setting_id = "'.$financial_year_id.'" and cw_leave_entry.trans_status = 1';
			$leave_entry_info = $this->db->query("CALL sp_a_run ('SELECT','$leave_entry_qry')");
			$leave_entry_rslt = $leave_entry_info->result();
			$leave_entry_info->next_result();	
			$leave_count      = (int)$leave_entry_rslt[0]->count;

			if($leave_count){
				return false;
			}else{*/
				return true;
			/*}*/
		}
	}

	//THIS CONDITION CHECK FOR OTHER REQUEST EXIST  #component value not used confirm it romove -ARN 07-03-2026
	public function check_exist_request_sts($component_value,$employee_code,$shift_date){
		$leave_financial_info = $this->get_leave_financial_details();
		$financial_year_id    = $leave_financial_info[0]->prime_leave_financial_year_id;	
		//------------------ DON'T DELETE ----------------------
		//check exist from time entry 
		/*$time_entry_qry       = 'SELECT count(cw_time_entry.prime_time_entry_id) as count FROM cw_time_entry WHERE cw_time_entry.employee_code = "'.$employee_code.'" and cw_time_entry.att_date = "'.$shift_date.'" and cw_time_entry.trans_status = 1';
		$time_entry_info      = $this->db->query("CALL sp_a_run ('SELECT','$time_entry_qry')");
		$time_entry_rslt      = $time_entry_info->result();
		$time_entry_info->next_result();	
		$time_count           = (int)$time_entry_rslt[0]->count;*/

		//CHECK EXIST FROM PERMISSION ENTRY 
		$permission_entry_qry  = 'SELECT count(cw_permission_entry.prime_permission_entry_id) as count FROM cw_permission_entry WHERE cw_permission_entry.employee_code = "'.$employee_code.'" and cw_permission_entry.permission_date = "'.$shift_date.'" and cw_permission_entry.leave_status in (1,2) and financial_setting_id = "'.$financial_year_id.'" and trans_status = 1';
		$permission_entry_info = $this->db->query("CALL sp_a_run ('SELECT','$permission_entry_qry')");
		$permission_entry_rslt = $permission_entry_info->result();
		$permission_entry_info->next_result();	
		$permission_count      = (int)$permission_entry_rslt[0]->count;
		
		//CHECK EXIST FROM MANUAL PUNCH ENTRY 
		$man_punch_check_qry   = 'SELECT COUNT(cw_manual_punch_entry.prime_manual_punch_entry_id) as count from cw_manual_punch_entry where cw_manual_punch_entry.employee_code = "'.$employee_code.'" and cw_manual_punch_entry.shift_date = "'.$shift_date.'" and cw_manual_punch_entry.leave_status in (1,2) and financial_setting_id = "'.$financial_year_id.'" 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;

		//CHECK EXIST FROM OVERTIME ENTRY 
		$overtime_check_qry   = 'SELECT COUNT(cw_overtime_entry.prime_overtime_entry_id) as count from cw_overtime_entry where cw_overtime_entry.employee_code = "'.$employee_code.'" and cw_overtime_entry.entry_date = "'.$shift_date.'" and cw_overtime_entry.approval_status in (1,2) and financial_setting_id = "'.$financial_year_id.'" and trans_status = 1';
		$overtime_check_info  = $this->db->query("CALL sp_a_run ('SELECT','$overtime_check_qry')");
		$overtime_check_rslt  = $overtime_check_info->result();
		$overtime_check_info->next_result();	
		$overtime_count       = (int)$overtime_check_rslt[0]->count;
		//|| $time_count
		if($permission_count || $mp_check_count || $overtime_count){
			return false;
		}else{
			return true;
		}
	}
	
	//============ PERMISSION VALIDATE EXIST CHECK ================================== 
	public function permission_setting_check($component_value,$employee_code,$permission_date,$shift_name,$in_time,$out_time,$total_time,$permission_type,$rkey){
		// -------- THIS QUERY NOT PERMENENTLY(ONCE COMPONENT VALUE DYNAMICALLY ADDED THEN IT REMOVE IT)
		$emp_detail_qry      = 'select role as category from cw_employees where cw_employees.employee_code = "'.$employee_code.'" and cw_employees.trans_status = 1';
		$emp_detail_info     = $this->db->query("CALL sp_a_run ('SELECT','$emp_detail_qry')");
		$emp_detail_result   = $emp_detail_info->result_array();
		$emp_detail_info->next_result();
		$component_value     = $emp_detail_result[0]['category'];
		// -------- THIS QUERY NOT PERMENENTLY(ONCE COMPONENT VALUE DYNAMICALLY ADDED THEN IT REMOVE IT)

		//COMPONENT AND SHIFT NAME BASED SELECT A PERMISSION SETTINGS DATA
		$permission_setting_qry     = 'SELECT allowed_per_month,allowed_per_day,no_of_permissions,permission_allow FROM cw_permission_setting WHERE FIND_IN_SET("'.$component_value.'", cw_permission_setting.component_value) and FIND_IN_SET("'.$shift_name.'", cw_permission_setting.shift_name) and trans_status = 1';
		$permission_setting_info    = $this->db->query("CALL sp_a_run ('SELECT','$permission_setting_qry')");
		$permission_setting_result  = $permission_setting_info->result();
		$permission_setting_info->next_result();

		$allow_per_month     = $permission_setting_result[0]->allowed_per_month;		
		$allow_per_month_arr = explode(':', $allow_per_month);
    	$allow_per_month     = round(($allow_per_month_arr[0]*60) + ($allow_per_month_arr[1]));

		$allow_per_day       = $permission_setting_result[0]->allowed_per_day;
		$allow_per_day_arr   = explode(':', $allow_per_day);
    	$allow_per_day       = round(($allow_per_day_arr[0]*60) + ($allow_per_day_arr[1]));

		$no_of_permissions   = $permission_setting_result[0]->no_of_permissions;
		$permission_allow    = (int)$permission_setting_result[0]->permission_allow;

		$salary_start_date   = "";
		$salary_end_date     = "";

		if($allow_per_month && $no_of_permissions && $allow_per_day){
			if(($allow_per_month < $total_time) && (int)$permission_type === 1){				
				echo json_encode(array('success' => FALSE, 'message' => "You Have Reached Maximum Hours per Month?"));
				exit(0);
			}else
			if(($allow_per_day < $total_time) && (int)$permission_type === 1){
				echo json_encode(array('success' => FALSE, 'message' => "You Have Reached Maximum Hours per Day?"));
				exit(0);
			}else{
				//GTE DEFAULT FINANCIAL YEAR
				$financial_info  = $this->get_leave_financial_details();
				$prime_financial_id    = $financial_info[0]->prime_leave_financial_year_id;	
				
				#Unused lines will comment confirm it then remove -ARN 07-03-2026
				// $starting_date         = date('Y-m-d',strtotime($financial_info[0]->starting_date));	
				// $ending_date           = date('Y-m-d',strtotime($financial_info[0]->ending_date));	
				//CHCEK MONTH DAY FOR THIS CATEGORY
				//TIME OF SETTING BASED SALARY START AND END DATE DETAILS
				$month_day_info        = $this->tos_day_info($employee_code,"4"); //DON'T CHANGE THIS 
				if(count($month_day_info ?? [])){
					if($rkey === "pastAtt"){
						$result            = $this->get_start_end_date($month_day_info['salary_start_date'],$month_day_info['salary_end_date']);
						$salary_start_date = date("Y-m-d",strtotime($result['start_date']));
						$salary_end_date   = date("Y-m-d",strtotime($result['end_date']));
						$year_end_date     = date("Y-m-d",strtotime($month_day_info['year_end_date']));
					}else{
						$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']));
					}
					
					$check_sts             = false;
					if($permission_date >= $salary_start_date && $permission_date <= $year_end_date){
						$check_sts         = true;
					}
					if($check_sts){
						$permission_entry_qry     = 'SELECT count(cw_permission_entry.prime_permission_entry_id) as count,SUM(total_minute) as total_time,employee_code,permission_date,shift_name FROM cw_permission_entry WHERE cw_permission_entry.employee_code = "'.$employee_code.'" and cw_permission_entry.permission_date >= "'.$salary_start_date.'" and cw_permission_entry.permission_date <= "'.$salary_end_date.'" and cw_permission_entry.leave_status in (1,2) and financial_setting_id = "'.$prime_financial_id.'" and trans_status = 1 and permission_type = "'.$permission_type.'" GROUP BY employee_code';
						$permission_entry_info    = $this->db->query("CALL sp_a_run ('SELECT','$permission_entry_qry')");
						$permission_entry_result  = $permission_entry_info->result();
						$permission_entry_info->next_result();	
						$permission_entry_count   = $permission_entry_result[0]->count;
						$month_permission_time    = $permission_entry_result[0]->total_time;
						
						if(((int)$permission_entry_count >= (int)$no_of_permissions) && (int)$permission_type === 1){
							echo json_encode(array('success' => FALSE, 'message' => "Already You Have Reached Number of Permission Limit per month?"));
							exit(0);
						}else{
							if($month_permission_time){
								$month_permission_time    = $month_permission_time + $total_time;
							}
							if(($month_permission_time > $allow_per_month) && (int)$permission_type === 1){
								echo json_encode(array('success' => FALSE, 'message' => "Already You Have Reached Maximum Hours per Month?"));
								exit(0);
							}else{
								$day_permission_time          = "";
								$permission_allow_day_qry     = 'SELECT count(cw_permission_entry.prime_permission_entry_id) as count,SUM(total_minute) as total_time FROM cw_permission_entry WHERE cw_permission_entry.employee_code = "'.$employee_code.'" and cw_permission_entry.permission_date = "'.$permission_date.'" and financial_setting_id = "'.$prime_financial_id.'" and cw_permission_entry.leave_status in (1,2) and trans_status = 1 GROUP BY employee_code';
								// and permission_type = "'.$permission_type.'"
								$permission_allow_day_info    = $this->db->query("CALL sp_a_run ('SELECT','$permission_allow_day_qry')");
								$permission_allow_day_result  = $permission_allow_day_info->result();
								$permission_allow_day_info->next_result();
								
								#Unused lines will comment confirm it then remove -ARN 07-03-2026
								// $exist_count                  = (int)$permission_allow_day_result[0]->count;	
								$day_permission_time          = $permission_allow_day_result[0]->total_time;
								if($day_permission_time){
									$day_permission_time      = $day_permission_time + $total_time;
								}
								// if($exist_count){
								// 	echo json_encode(array('success' => FALSE, 'message' => "Permission Already Exist for the Same Date.!"));
								// 	exit(0);
								// }else
								if(($day_permission_time >= $allow_per_day) && (int)$permission_type === 1){
									echo json_encode(array('success' => FALSE, 'message' => "Already You Have Reached Maximum Hours per Day?"));
									exit(0);
								}else{
									//CHECK PERMISSION IN AND OUT TIME BASED ON PERMISSION SETTING (PERMISSION ALLOW ANYTIME INPUT)
									//FUNCTION FOR GET A SHIFT IN AND OUT TIME DR CODE
									$shift_master_rslt  = $this->shift_time_qry($shift_name);							
									#Unused lines will comment confirm it then remove -ARN 07-03-2026
									// $shift_id           = $shift_master_rslt[0]->prime_shift_master_id;
									$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){
										echo json_encode(array('success' => false, 'message' => 'Shift Time not Added to Shift Master.!'));	
										exit(0);
									}else{
										if($permission_allow === 2){
											// if(($from_time > $in_time) || ($to_time < $out_time)){
											// 	echo json_encode(array('success' => false, 'message' => 'Permission Only Allow Shift Start to Shift End Time.!'));
											// 	exit(0);
											// }
											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.!'));
												exit(0);
											}else{
												return true;
											}
										}else
										if($permission_allow === 1){
											
											//PERMISSION IN AND OUT TIME VALIDATE BASED ON SHIFT MASTER
											// return $this->in_and_out_date_valid($shift_master_rslt,$permission_date,$in_time,$out_time);	
											return true;
										}
									}		
								}
							}
						}
					}else{
						echo json_encode(array('success' => FALSE, "message" => "Don't Add Permission Request.! 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);
				}
			}
		}else{
			echo json_encode(array('success' => FALSE, 'message' => "Please Check in Permission Setting for All Required Details are Added or not.!"));
			exit(0);
		}
	}

	public function total_time_cal($in_date,$out_date,$in_time,$out_time,$in_time_count,$out_time_count){
		$total_time      = "";
		$days            = "";
		if((int)$in_time_count === 2){
			$in_time       = $in_time.":00";
		}
		if((int)$out_time_count === 2){
			$out_time      = $out_time.":00";
		}
		//CONVERT STRING TO DATE FORMAT
		if($in_date === $out_date){
			if($in_time < $out_time){
				$in_time     = new DateTime($in_time);
		   		$out_time    = new DateTime($out_time);
		   		$timeDiff    = $in_time->diff($out_time);
		   		$days        = (int)$timeDiff->days;
		   		$total_time  = $timeDiff->format("%H:%I:%S");
			}else{
				$total_time  = "";
			}	
		}
		else{
			$in_date     = new DateTime($in_date." ".$in_time);
			$out_date    = new DateTime($out_date." ".$out_time);
			$timeDiff    = $in_date->diff($out_date);
			$days        = (int)$timeDiff->days;
			$total_time  = $timeDiff->format("%H:%I:%S");
		}
		if($total_time && ($days === 0 || $days === 1)){
			return $total_time;
		}else{
			return false;
		}
	}

	//function for get hours and minutes in two degits format
	public function hours_mins_cal($hrs_mins){
		$get_hrs            = floor($hrs_mins / 60);
		$get_mins           = ($hrs_mins -   floor($hrs_mins / 60) * 60);
		//ternary operator using for get a hour and minutes with two digits format
		$get_hrs_format     = (strlen((string)$get_hrs) === 1) ? ('0'.$get_hrs) : ($get_hrs);
		$get_mins_format    = (strlen((string)$get_mins) === 1) ? ('0'.$get_mins) : ($get_mins);
		
		$total_hrs_mins     = $get_hrs_format.':'.$get_mins_format;
		return $total_hrs_mins;
	} 
	//Convert Hour Format into mins
	public function hourstomins($hours){
		$timesplit=explode(':',$hours);
    	$min=($timesplit[0]*60)+($timesplit[1])+($timesplit[2]>30?1:0);
    	return $min;
	}

	//FUNCTION FOR EMPLOYEE SHIFT NAME AND PUNCH IN AND OUT TIME GET
	public function emp_shift_punch_time(){
		//ENCRYPTION
		$encString      = file_get_contents('php://input');
		$_POST          = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
		$employee_code      = $this->input->post('employee_code');
		$shift_date         = date("Y-m-d",strtotime($this->input->post('shift_date')));

		$punch_time_qry     = 'select cw_shift_master.shift_name,cw_time_entry.punch_in,cw_time_entry.punch_out from cw_time_entry INNER JOIN cw_shift_master on cw_shift_master.prime_shift_master_id = cw_time_entry.shift_id where cw_time_entry.employee_code = "'.$employee_code.'" and cw_time_entry.att_date = "'.$shift_date.'" and cw_time_entry.trans_status = 1';

		$punch_time_info    = $this->db->query("CALL sp_a_run ('SELECT','$punch_time_qry')");
		$punch_time_result  = $punch_time_info->result();
		$punch_time_info->next_result();
		$shift_name         = $punch_time_result[0]->shift_name;
		$punch_in           = $punch_time_result[0]->punch_in;
		$punch_out          = $punch_time_result[0]->punch_out;

	
		if($punch_in !== NULL && $punch_in !== "0000-00-00 00:00:00"){
			$punch_in       = date("d-m-Y H:i",strtotime($punch_in));
		}else{
			$punch_in       = '';
		}

		if($punch_out !== NULL && $punch_out !== "0000-00-00 00:00:00"){
			$punch_out      = date("d-m-Y H:i",strtotime($punch_out));
		}else{
			$punch_out       = '';
		}
		
		if($punch_in || $punch_out){
			echo json_encode(array('success' => TRUE, 'message' => "Success.!", 'shift_name' => $shift_name, 'punch_in' => $punch_in, 'punch_out' => $punch_out));
		}else{
			echo json_encode(array('success' => FALSE, 'message' => "Punch Data not Available.!", 'shift_name' => $shift_name));
		}
	}

	//FOR MANUAL PUNCH VALIDATION
	public function manual_punch_shift(){
		//ENCRYPTION
		$encString      = file_get_contents('php://input');
		$_POST          = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
		$employee_code      = $this->input->post('employee_code');
		#Unused lines will comment confirm it then remove -ARN 07-03-2026
		// $day_type        = $this->input->post('day_type');
		$mp_treat_time_log  = $this->input->post('mp_treat_time_log');
		$shift_date         = date("Y-m-d",strtotime($this->input->post('shift_date')));
		$shift_time_qry     = 'select cw_shift_import.shift_name,cw_shift_import.shift_date as shift_date,cw_shift_master.shift_status,cw_shift_master.in_time as import_in_time,cw_shift_master.out_time as import_out_time,cw_shift_master.from_time as from_time,cw_shift_master.to_time as to_time,cw_shift_master.first_half as first_half,cw_shift_master.second_half as second_half 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();

		// IN TIME OUT TIME IN DATE OUT DATE PROCESS
		$shift_status       = (int)$shift_time_result[0]->shift_status;
		$from_time          = $shift_time_result[0]->from_time;
		$to_time            = $shift_time_result[0]->to_time;
		$today              = $shift_date;
		$tomorrow           = date('Y-m-d', strtotime($shift_date . ' +1 day'));
		$range_from         = "";
		if($shift_status === 1){
			// Current day IN → Current day OUT
			$range_from     = $today . ' ' . $from_time;
			$range_to       = $today . ' ' . $to_time;

		}else
		if($shift_status === 2){
			// Current day IN → Tomorrow OUT
			$range_from     = $today . ' ' . $from_time;
			$range_to       = $tomorrow . ' ' . $to_time;

		}else
		if($shift_status === 3){
			// Tomorrow IN → Tomorrow OUT
			$range_from     = $tomorrow . ' ' . $from_time;
			$range_to       = $tomorrow . ' ' . $to_time;
		}
		$in_date            = date("d-m-Y", strtotime($range_from));
		$out_date           = date("d-m-Y", strtotime($range_to));
		$in_time            = date("H:i", strtotime($range_from));
		$out_time           = date("H:i", strtotime($range_to));

		if($shift_time_result){
			$min_date_time  = "";
			$max_date_time  = "";
			$min_date       = "";
			$min_time       = "";
			$max_date       = "";
			$max_time       = "";
			if((int)$mp_treat_time_log === 1){
				$time_entry_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 = "'.$shift_date.'" and cw_time_entry.trans_status = 1';
				$time_entry_date_info = $this->db->query("CALL sp_a_run ('SELECT','$time_entry_date_qry')");
				$time_entry_date_rslt = $time_entry_date_info->result_array();
				$time_entry_date_info->next_result();
				$min_date_time        = $time_entry_date_rslt[0]['min_log_date'];
				$max_date_time        = $time_entry_date_rslt[0]['max_log_date'];
				
				if($min_date_time !== NULL && $min_date_time !== "0000-00-00 00:00:00"){
					$min_date             = date("d-m-Y",strtotime($min_date_time));
					$min_time             = date("H:i",strtotime($min_date_time));
				}else{
					$min_date = $in_date;
					$min_time = $in_time;
				}

				if($max_date_time !== NULL && $max_date_time !== "0000-00-00 00:00:00"){
					$max_date             = date("d-m-Y",strtotime($max_date_time));
					$max_time             = date("H:i",strtotime($max_date_time));
				}else{
					$max_date = $out_date;
					$max_time = $out_time;
				}
			}
			echo json_encode(array('success' => TRUE, 'shift_result' => $shift_time_result, 'min_date' => $min_date, 'min_time' => $min_time, 'max_date' => $max_date, 'max_time' => $max_time));
		}else{
			echo json_encode(array('success' => FALSE, 'message' => "Shift not Allocated in this Date!"));
		}
	}

	//TWO DATE TIME DIFFERENCE FUNCTION for TIME ENTRY 
	public function date_differ_fun($from_time_date,$to_time_date){
		$time1       = new DateTime($from_time_date);
		$time2       = new DateTime($to_time_date);
		$interval    = $time1->diff($time2);
		$hour        = ($interval->format("%H")) * 60;
		$min         = $interval->format("%I");
		$rslt        = $hour + $min;
		return $rslt;
	}

	// ------- FUNCTION FOR DYNAMICALLY GENERAL SETTING(LEAVE ENTRY) BASED COMPONENT VALUE(LABEL NAME) GET -----
	public function gen_setting_comp_col($entry_param_type){
		//SLEECT QUERY FORM SETTING AND GENERAL SETTING BASED LABEL NAME GET
		$sel_comp_qry        = 'SELECT cw_form_setting.label_name FROM cw_general_setting INNER JOIN cw_form_setting ON cw_general_setting.components = cw_form_setting.prime_form_id where cw_general_setting.trans_status = 1 and cw_form_setting.trans_status = 1 and cw_general_setting.entry_parameter_type = '.$entry_param_type.'';
		$sel_comp_info       = $this->db->query("CALL sp_a_run ('SELECT','$sel_comp_qry')");
		$sel_comp_rslt       = $sel_comp_info->result_array();
		$sel_comp_info->next_result();

		$component_col       = "";
		if(!empty($sel_comp_rslt)){
			$component_col       = $sel_comp_rslt[0]['label_name'];
		}
		return $component_col;
	}

	public function time_log_insert($post_data,$prime_financial_id,$leave_status){
		$created_on        = date("Y-m-d H:i:s");
		$prime_ins_value   = "";
		foreach($post_data as $index => $data){
			foreach($data as $key => $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 === "in_time"){
					$in_time         = $value;
				}
				if($key === "out_time"){
					$out_time        = $value;
				}
				if($key === "day_type"){
					$shift_day_type  = (int)$value;
				}
			}
			$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";
			}
			$from_date_time     = $in_date." ".$in_time;
			$to_date_time       = $out_date." ".$out_time;
			$current_year       = date("Y");
			if((int)$leave_status === 2){
				$emp_device_code_qry ='select device_code from cw_employees where employee_code="'.$employee_code.'" and trans_status=1';
				$device_code_info = $this->db->query("CALL sp_a_run ('SELECT','$emp_device_code_qry')");
				$device_code_rslt = $device_code_info->result();
				$device_code_info->next_result();
				$device_code  = $device_code_rslt[0]->device_code;
				$prime_ins_value    .= '("MAN01","'.$from_date_time.'","in","'.$device_code.'","'.$this->logged_id.'","'.$created_on.'"),';
				$prime_ins_value    .='("MAN02","'.$to_date_time.'","out","'.$device_code.'","'.$this->logged_id.'","'.$created_on.'"),';
			}			
		}
		if($prime_ins_value){
			$prime_ins_val   = rtrim($prime_ins_value,",");
			$in_out_time_ins_qry   = 'INSERT INTO cw_time_log (device_id,log_date,record_type,user_id,trans_created_by,trans_created_date) VALUES '.$prime_ins_val;
			$in_out_time_ins_info  = $this->db->query("CALL sp_a_run ('INSERT','$in_out_time_ins_qry')");
			$in_out_time_ins_rslt  = $in_out_time_ins_info->result();
			$in_out_time_ins_info->next_result();
			$in_out_time_ins_id    = $in_out_time_ins_rslt[0]->ins_id;	
			if($in_out_time_ins_id){
				$action_status = 3; //Approved						
			}else{
				echo json_encode(array('success' => FALSE, 'message' => 'Time Log Insert Query Error.!'));
				exit(0);
			}
		}
	}

	//FUNCTION FOR BUILD ARRAY [LEAVE ENTRY TABLE AND ONDUTY ENTRY TABLE]
	public function build_common_valid_array(){
		//TIME OF SETTING BASED SALARY START AND END DATE DETAILS
		$last_payroll_month   = 'select max(date_format(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y") , "%Y-%m")) as max_month from cw_transactions where trans_status = 1';
		$last_payroll_info    = $this->db->query("CALL sp_a_run ('SELECT','$last_payroll_month')");
		$last_payroll_rslt    = $last_payroll_info->result();
		$last_payroll_info->next_result();
		$last_pay_month       = $last_payroll_rslt[0]->max_month;
		
		$nxt_month            = date("d-m-Y", strtotime($last_pay_month."-01"));
		//GET SALARY FROM DATE
		$month_day_result     = $this->tos_day_qry_fun("3");
		$day_start            = $month_day_result[0]->day_start;
		if(!$day_start || $day_start === ""){
			$day_start = "01";
		}
		#Unused lines will comment confirm it then remove -ARN 07-03-2026
		// $day_end              = $month_day_result[0]->day_end;
		$salary_start_date    = date("Y-m",strtotime($nxt_month))."-".$day_start;
		//CHECK LEAVE ENTRY EXIST 
		$sel_leave_entry_qry  = 'select employee_code,leave_date,leave_count,date_type from cw_leave_entry where leave_date >= "'.$salary_start_date.'" and trans_status = 1 and leave_status in(1,2)';
		$leave_entry_info     = $this->db->query("CALL sp_a_run ('SELECT','$sel_leave_entry_qry')");
		$leave_entry_result   = $leave_entry_info->result_array();
		$leave_entry_info->next_result();
		foreach($leave_entry_result as $arr){
			$leave_entry_arr[$arr['employee_code']][$arr['leave_date']][$arr['date_type']]=$arr['leave_count'];
		}
		//CHECK ONDUTY ENTRY EXIST  
		$sel_onduty_entry_qry  ='select employee_code,on_duty_date,date_type,on_duty_count from cw_on_duty_entry where on_duty_date >= "'.$salary_start_date.'" and trans_status = 1 and on_duty_status in (1,2)';
		$sel_onduty_info       = $this->db->query("CALL sp_a_run ('SELECT','$sel_onduty_entry_qry')");
		$sel_onduty_result     = $sel_onduty_info->result_array();
		$sel_onduty_info->next_result();
		foreach($sel_onduty_result as $arr){
			$onduty_entry_arr[$arr['employee_code']][$arr['on_duty_date']][$arr['date_type']]=$arr['on_duty_count'];
		}
		$result = array();
		// MERGE ONDUTY INTO RESULT
		foreach ($onduty_entry_arr as $key => $onduty_dates){
			foreach ($onduty_dates as $date => $onduty_values){
				if(isset($result[$key][$date])){
					// IF THE KEY AND DATE EXIST IN BOTH ARRAYS SUM THE VALUES 
					foreach ($onduty_values as $subkey => $subvalue) {
						$result[$key][$date][$subkey] += $subvalue;
					}
				}else{
					// IF THE KEY AND DATE DO NOT EXIST IN COPY VALUES FROM OUDTY ARRAY 
					$result[$key][$date] = $onduty_values;
				}
			}
		}			
		// MERGE LEVAE ENTRY ARRAY INTO RESULT 
		foreach ($leave_entry_arr as $key => $leave_dates){
			foreach ($leave_dates as $date => $leave_values){
				if(isset($result[$key][$date])){
					// IF THE KEY AND DATE EXIST IN BOTH ARRAYS SUM THE VALUES 
					foreach ($leave_values as $subkey => $subvalue) {
						$result[$key][$date][$subkey] += $subvalue;
					}
				}else{
					// IF THE KEY AND DATE DO NOT EXIST IN COPY VALUES FROM LEAVE ENTRY ARR I
					$result[$key][$date] = $leave_values;
				}
			}
		}
		return $result;		
	}


	//TIME LOG FUNCTION ONLY FOR MP ENTRY
	public function time_log($post_data,$prime_financial_id,$leave_status){
		// print_r($post_data); die;
		$created_on = date("Y-m-d H:i:s");
		foreach ($post_data as $key => $value) {
			if($key === "employee_code"){
				$employee_code    = $value;
			}
			if($key === "prime_request_id"){
				$prime_request_id = $value;
			}
			if($key === "request_type"){
				$request_type     = (int)$value;
			}
			if($key === "shift_date"){
				$shift_date  = $value;
			}
			if($key === "in_date"){
				$in_date  = $value;
			}
			if($key === "out_date"){
				$out_date    = $value;
			}
			if($key === "in_time"){
				$in_time         = $value;
			}
			if($key === "out_time"){
				$out_time        = $value;
			}
			if($key === "day_type"){
				$shift_day_type  = (int)$value;
			}
			if($key === "device_code"){
				$device_code     = $value;
			}
		}
		if(!$device_code){	
			echo json_encode(array('success' => FALSE, 'message' => 'Device Code Should not Empty..!'));
			exit(0);	
		}
		//WE ADD A TIME WITH SECONDS BASED ON IN TIME AND OUT TIME LENGTH
		$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";
		}
		$from_date_time     = $in_date." ".$in_time;
		$to_date_time       = $out_date." ".$out_time;
		$current_year       = date("Y");
		//IF TIME LOG INSERT ONLY FOR MP APPROVAL 
		if((int)$leave_status === 2){
			//TIME LOG INSERT PROCESS	
			$prime_ins_value    = '("MAN01","'.$from_date_time.'","in","'.$device_code.'","'.$this->logged_id.'","'.$created_on.'"),("MAN02","'.$to_date_time.'","out","'.$device_code.'","'.$this->logged_id.'","'.$created_on.'")';

			$in_out_time_ins_qry   = 'INSERT INTO cw_time_log (device_id,log_date,record_type,user_id,trans_created_by,trans_created_date) VALUES '.$prime_ins_value;
			$in_out_time_ins_info  = $this->db->query("CALL sp_a_run ('INSERT','$in_out_time_ins_qry')");
			$in_out_time_ins_rslt  = $in_out_time_ins_info->result();
			$in_out_time_ins_info->next_result();
			$in_out_time_ins_id    = $in_out_time_ins_rslt[0]->ins_id;	
			if(!$in_out_time_ins_id){	
				echo json_encode(array('success' => FALSE, 'message' => 'Time Log Insert Query Error.!'));
				exit(0);	
			}
		}else
		if((int)$leave_status === 4){
			$del_time_log_qry   = 'DELETE FROM cw_time_log WHERE cw_time_log.user_id = "'.$device_code.'" and cw_time_log.device_id in ("MAN01","MAN02") and log_date in ("'.$from_date_time.'","'.$to_date_time.'")';
			if(!$this->db->query("CALL sp_a_run ('RUN','$del_time_log_qry')")){
				echo json_encode(array('success' => FALSE, 'message' => 'Time Log Delete Query Error.!'));
				exit(0);	
			}
		}
		//TIME ENTRY PROCEDURE CALLING
		$info              = $this->db->query("CALL itsp_prcatt ('$shift_date','$shift_date','$employee_code')");
		$result            = $info->result();
		$info->next_result();
		
		if(!$result){
			echo json_encode(array('success' => FALSE, 'message' => "Time Entry Procedure Error.!"));
			exit(0);
		}else{
			//TIME ENTRY ACTION STATUS UPDATE
			$action_status     = '';
			if($leave_status === 1){
				$action_status = 2;
			}else
			if($leave_status === 2){
				$action_status = 3; //Approved
			}else
			if($leave_status === 3){
				$action_status = 4;
			}else
			if($leave_status === 4){
				$action_status = 5; //Cancelled
			}
			if($action_status){
				$upd_time_entry = 'UPDATE cw_time_entry SET action_status = "'.$action_status.'",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 = "'.$shift_date.'" and cw_time_entry.trans_status = 1';
				$this->db->query("CALL sp_a_run ('UPDATE','$upd_time_entry')");
				return array('success' => "true", 'message' => 'proceed');
			}
		}	
	}	

	//TIME ENTRY FUNCTION
	public function time_entry($post_data,$prime_financial_id,$leave_status){
		foreach ($post_data as $key => $value) {
			if($key === "employee_code"){
				$employee_code    = $value;
			}
			if($key === "prime_request_id"){
				$prime_request_id = $value;
			}
			if($key === "request_type"){
				$request_type     = (int)$value;
			}
			if($key === "leave_type"){
				$leave_type       = $value;
			}
			if($key === "from_date"){
				$from_date        = $value;
			}
			if($key === "from_date_type"){
				$from_date_type   = (int)$value;
			}
			if($key === "to_date"){
				$to_date          = $value;
			}
			if($key === "to_date_type"){
				$to_date_type     = (int)$value;
			}
			if($key === "shift_date"){
				$shift_date  = $value;
			}
			if($key === "in_date"){
				$in_date  = $value;
			}
			if($key === "out_date"){
				$out_date    = $value;
			}
			if($key === "in_time"){
				$in_time         = $value;
			}
			if($key === "out_time"){
				$out_time        = $value;
			}
			if($key === "day_type"){
				$shift_day_type  = (int)$value;
			}
			if($key === "device_code"){
				$device_code     = $value;
			}
			if($key === "cancellation_request"){
				$can_request     = (int)$value;
			}
		}		
		//FOR MANUAL PUNCH
		if($request_type === 7){
			$from_date   = $shift_date;
			$to_date     = $shift_date;
		}
		//WE ADD A TIME WITH SECONDS BASED ON IN TIME AND OUT TIME LENGTH
		$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";
		}

		$day_status_legend_arr  = "";
		$time_log_arr           = ""; 
		$time_entry_arr         = "";
		$shift_time_arr         = "";
		$from_date_time         = "";
		$to_date_time           = "";
		//FOR MANUAL PUNCH
		if($request_type === 7){
			$from_date_time = $in_date." ".$in_time;
			$to_date_time   = $out_date." ".$out_time;
		}
		//GET DATE RAGE FOR DATE BY DATE IN INSERT OR UPDATE TO TIME ENTRY TABLE
		$date_range        = "";
		if($request_type === 7){
			$date_range    = $this->getDatesFromRange($shift_date, $shift_date);
		}else{
			$date_range    = $this->getDatesFromRange($from_date, $to_date);
		}
		
		$get_year          = date('Y',strtotime($from_date));
		$today             = date('Y-m-d');

		$mp_treat_time_log = $this->company_info[0]->mp_treat_as;

		//SELECT QUERY FOR GET DAY DESCRIPTION FOR CHECK VALIDATION IN TIME ENTRY TABLE
		$day_status_legend_qry  = 'select legends,day_description,day_type from cw_day_status_legends where cw_day_status_legends.trans_status = 1';
		$day_status_legend_info = $this->db->query("CALL sp_a_run ('SELECT','$day_status_legend_qry')");
		$day_status_legend_rslt = $day_status_legend_info->result_array();
		$day_status_legend_info->next_result();

		$day_status_legend_arr  = array_reduce($day_status_legend_rslt, function($result, $arr){
	    	$result[$arr['legends']] = $arr;
	    	return $result;
		}, array());

		// ---- FUNCTION FOR DYNAMICALLY GENERAL SETTING(LEAVE ENTRY) BASED COMPONENT VALUE(LABEL NAME) GET 
		$component_col       = $this->gen_setting_comp_col("3");
		if($component_col){
			$sel_comp_col    = ','.$component_col.' as component_value';
		}else{
			echo json_encode(array('success' => FALSE, 'message' => 'Enty Parameter Type not Mapped for Leave Entry in General Setting Module.!'));
			exit(0);
		}
		//SELECT EMPLOYEE DETAILS FROM EMPLOYEE MASTER BY DR (5JUL22)
		$emp_detail_qry      = 'select role as category'.$sel_comp_col.' from cw_employees where cw_employees.employee_code = "'.$employee_code.'" and cw_employees.trans_status = 1';
		$emp_detail_info     = $this->db->query("CALL sp_a_run ('SELECT','$emp_detail_qry')");
		$emp_detail_result   = $emp_detail_info->result_array();
		$emp_detail_info->next_result();
		$category            = $emp_detail_result[0]['category'];
		$component_value     = $emp_detail_result[0]['component_value'];

		//get exist data from time log table
		$time_log_qry      = 'select date_format(str_to_date(cw_time_log.log_date, "%Y-%m-%d %H:%i:%s"),"%Y-%m-%d") as log_date,device_id,record_type from cw_time_log where cw_time_log.user_id = "'.$device_code.'" and date_format(str_to_date(cw_time_log.log_date, "%Y-%m-%d %H:%i:%s"),"%Y-%m-%d") between ("'.$from_date.'") and ("'.$to_date.'") and cw_time_log.trans_status = 1';
		$time_log_info     = $this->db->query("CALL sp_a_run ('SELECT','$time_log_qry')");
		$time_log_result   = $time_log_info->result_array();
		$time_log_info->next_result();

		$time_log_arr      = array_reduce($time_log_result, function($result, $arr){			
	    	$result[$arr['log_date']] = $arr;
	    	return $result;
		}, array());
		
		//SELECT QUERY FOR CHECK A EXISTS DATA FROM TIME ENTRY TABLE 
		$time_entry_qry      = 'select * 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_entry_arr[$time_att_date]  = $time_val;
		}
		// $time_entry_arr      = array_reduce($time_entry_result, function($result, $arr){			
	    // 	$result[$arr['att_date']] = $arr;
	    // 	return $result;
		// }, array());

		///QUERY FOR GET A SHIFT DATE AND IN AND OUT TIME FROM SHIFT MASTER AND SHIFT IMPORT TABLES FOR MANUAL PUNCH REQUEST APPROVAL 
		$shift_time_qry     = 'select cw_shift_master.prime_shift_master_id,cw_shift_import.employee_code as employee_code,cw_shift_master.shift_name,cw_shift_import.shift_date as shift_date,cw_shift_import.from_date as from_date,cw_shift_master.from_time as from_time,cw_shift_import.to_date as to_date,cw_shift_master.to_time as to_time,cw_shift_master.first_half as first_half,cw_shift_master.second_half as second_half,cw_shift_master.shift_status as shift_status,(TRUNCATE(TIME_TO_SEC(cw_permission_setting.grace_time) / 60 ,2)) as grace_min,(TRUNCATE(TIME_TO_SEC(cw_permission_setting.late_hrs_max) / 60 ,2)) as late_max_min,excess_hours_allow,early_going_add_to_late as early_go_late from cw_shift_import inner join cw_shift_master on cw_shift_master.prime_shift_master_id = cw_shift_import.shift_name inner join cw_permission_setting on FIND_IN_SET(cw_shift_master.prime_shift_master_id, cw_permission_setting.shift_name) where cw_shift_import.employee_code = "'.$employee_code.'" and cw_shift_import.shift_date between ("'.$from_date.'") and ("'.$to_date.'") and FIND_IN_SET("'.$category.'", cw_permission_setting.component_value) and cw_shift_import.trans_status = 1';
		//THIS CODE IS REQUIRED FOR UPDATE IN ABOVE QUERY
		// and FIND_IN_SET("'.$component_value.'", cw_permission_setting.component_value)

		$shift_time_info   = $this->db->query("CALL sp_a_run ('SELECT','$shift_time_qry')");
		$shift_time_result = $shift_time_info->result_array();
		$shift_time_info->next_result();

		$shift_time_arr      = array_reduce($shift_time_result, function($result, $arr){			
	    	$result[$arr['shift_date']] = $arr;
	    	return $result;
		}, array());
		if($request_type === 7){
			if(!$shift_time_arr){
				echo json_encode(array('success' => false, 'message' => 'Shift Not Allocated in this Date'));
				exit(0);
			}
		}
		
		//GET LEAVE NAME INTERVENING TYPE AND INTERVENING HOLIDAYS FROM LEAVE CREATION TABLE
		$leave_creation_qry    = 'SELECT count(*) as creation_count,leave_opening,intervening_holidays,intervening_type,leave_description,leave_name 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;

		//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'];	

		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;
			$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());
		}
		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;
			$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");
		}
		
		$time_entry_ins_value   = "";
		$time_entry_upd_value   = "";
		$status                 = "true"; 
		$msg                    = "One or More Date(s) Already Exists in Attendance Entry";
		$end_key                = end(array_keys($date_range));
		foreach ($date_range as $key => $common_date){
			$prime_time_id      = $time_entry_arr[$common_date]['prime_time_entry_id'];
			$punch_in           = $time_entry_arr[$common_date]['punch_in'];
			$punch_out          = $time_entry_arr[$common_date]['punch_out'];
			$manual_in          = $time_entry_arr[$common_date]['manual_in'];
			$manual_out         = $time_entry_arr[$common_date]['manual_out'];
			$late_in            = $time_entry_arr[$common_date]['late_in'];
			$early_out          = $time_entry_arr[$common_date]['early_out'];
			$early_in           = $time_entry_arr[$common_date]['early_in'];
			$excess_out         = $time_entry_arr[$common_date]['excess_out'];
			$total_work_hours   = $time_entry_arr[$common_date]['total_work_hours'];
			$total_late_hours   = $time_entry_arr[$common_date]['total_late_hours'];
			$total_excess_hours = $time_entry_arr[$common_date]['total_excess_hours'];
			$entry_flag         = $time_entry_arr[$common_date]['entry_flag'];
			$update_flag        = $time_entry_arr[$common_date]['update_flag'];
			$first_half_status  = $time_entry_arr[$common_date]['first_half_status'];
			$first_half_count   = $time_entry_arr[$common_date]['first_half_count'];
			$second_half_status = $time_entry_arr[$common_date]['second_half_status'];
			$second_half_count  = $time_entry_arr[$common_date]['second_half_count'];

			$day_type           = $time_entry_arr[$common_date]['whole_day_status'];
			$check_day_type     = (int)$day_status_legend_arr[$day_type]['day_type'];

			//GET VALUE FROM SHIFT TIME ARRAY
			$shift_master_id    = $shift_time_arr[$common_date]['prime_shift_master_id'];
			$shift_name         = $shift_time_arr[$common_date]['shift_name'];
			$from_shift_date    = $shift_time_arr[$common_date]['from_date'];
			$from_time          = $shift_time_arr[$common_date]['from_time'];
			$to_shift_date      = $shift_time_arr[$common_date]['to_date'];
			$to_time            = $shift_time_arr[$common_date]['to_time'];
			$first_half         = $shift_time_arr[$common_date]['first_half'];
			$second_half        = $shift_time_arr[$common_date]['second_half'];
			$shift_status       = (int)$shift_time_arr[$common_date]['shift_status'];
			
			//DR CODE FOR MANUAL PUNCH 
			$grace_min          = $shift_time_arr[$common_date]['grace_min'];
			$late_max_min       = $shift_time_arr[$common_date]['late_max_min'];
			$excess_hr_allow    = (int)$shift_time_arr[$common_date]['excess_hours_allow'];
			$early_go_late      = (int)$shift_time_arr[$common_date]['early_go_late'];
			$total_ded_time     = $grace_min + $late_max_min;
			$from_time_date     = date("Y-m-d H:i:s", strtotime($shift_date.' '.$from_time));
			$first_half_date    = date("Y-m-d H:i:s", strtotime($shift_date.' '.$first_half));
			$second_half_date   = date("Y-m-d H:i:s", strtotime($shift_date.' '.$second_half));
			$to_time_date       = date("Y-m-d H:i:s", strtotime($shift_date.' '.$to_time));

			//CONDITION FOR CURRENT IN TOMORROW OUT
			//for 1st half end second half start and shift end 
			if($from_time_date > $first_half_date){
				$first_half_date   = date("Y-m-d H:i:s", strtotime("+1 days",strtotime($first_half_date)));
				$second_half_date  = date("Y-m-d H:i:s", strtotime("+1 days",strtotime($second_half_date)));
				$to_time_date      = date("Y-m-d H:i:s", strtotime("+1 days",strtotime($to_time_date)));
			}else//for second half start and shift end  
			if($from_time_date > $second_half_date){
				$second_half_date  = date("Y-m-d H:i:s", strtotime("+1 days",strtotime($second_half_date)));
				$to_time_date      = date("Y-m-d H:i:s", strtotime("+1 days",strtotime($to_time_date)));
			}else//for shift end  
			if($second_half_date > $to_time_date){
				$to_time_date      = date("Y-m-d H:i:s", strtotime("+1 days",strtotime($to_time_date)));
			}
			//CHECK WEEKOFF DAY AND HOLIDAY DATE
			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)));
				$day           = $days_arr[$get_day];
				$week_no       = $this->weekOfMonth(strtotime($common_date)); 
				$week          = $week_arr[$week_no];
				$weekoff_value = $weekoff_result[$day][$week];			
			}
			// CHECK DATE IF [HOLIDAY OR NOT] OR [WEEK OFF DAY OR NOT]
			if($holiday_entry === 2){
				$get_common_holiday  = $holiday_result[$common_date]['holiday_date'];
			}	
			//IF APPROVAL MODULE FOR APPROVER HAS REJECTED THE REQUEST
			if($this->control_name === "approval" && $leave_status === 3){
				if($can_request === 2 && $prime_time_id){
					//UPD QUERY VALUE
					$time_entry_upd_value .= '("'.$prime_time_id.'","4","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
					// ,"'.$shift_master_id.'"
				}
			}else{
				//THIS VARIABLE FOR CHECK IF COMMOM DATE WAS HOLIDAY OR WEEKOFF BECAUSE HOLIDAY OR WEEKOFF DAYS NOT INSERT OR UPDATE TO TIME ENTRY TABLE
				$ins_upd_rslt       = 1;
				//MANUAL PUNCH REQUEST
				if($request_type === 7){
					//check time log table for same date already punch add or not
					$log_date       = $time_log_arr[$common_date]['log_date'];
					//DATE FOR CHECK A GRACE TIME AND MAX LATE REACH SO ADD A INVALID (FOR MANUAL PUNCH REQUEST BY DR 5JUL22)
					$grace_from_time_dte   = date("Y-m-d H:i:s", strtotime("+$total_ded_time minutes",strtotime($from_time_date)));
					$grace_second_half_dte = date("Y-m-d H:i:s", strtotime("+$total_ded_time minutes", strtotime($second_half_date)));
					//TO MANUAL PUNCH FOR LATE IN EARLY OUT AND EXCESS IN AND EXCESS OUT CALCULATION BY DR 5JUL22
					if($shift_day_type === 1 || $shift_day_type === 2){
						//FROM GRACE TIME DATE SHOULD CREATE FOR CHECK A LATE AFTER GRACE TIME REACHED ENTRY ONLY (FOR FULL DAY AND 1ST HALF)
						$from_grace_time   = date("Y-m-d H:i:s", strtotime("+$grace_min minutes",strtotime($from_time_date)));
						if($from_grace_time < $from_date_time){
							$late_in       = $this->date_differ_fun($from_time_date,$from_date_time);
						}else
						if($from_time_date > $from_date_time){
							$early_in      = $this->date_differ_fun($from_date_time,$from_time_date);
						}
						if($shift_day_type === 1){
							if($to_time_date < $to_date_time){
								$excess_out   = $this->date_differ_fun($to_time_date,$to_date_time);
							}else
							if($to_time_date > $to_date_time){
								$early_out    = $this->date_differ_fun($to_date_time,$to_time_date);
							}
						}else
						if($shift_day_type === 2){
							if($first_half_date < $to_date_time){
								$excess_out   = $this->date_differ_fun($first_half_date,$to_date_time);
							}else
							if($first_half_date > $to_date_time){
								$early_out    = $this->date_differ_fun($to_date_time,$first_half_date);
							}
						}
					}else
					if($shift_day_type === 3){
						//FROM GRACE TIME DATE SHOULD CREATE FOR CHECK A LATE AFTER GRACE TIME REACHED ENTRY ONLY (FOR 2ND HALF)
						$second_half_grace_time  = date("Y-m-d H:i:s", strtotime("+$grace_min minutes",strtotime($second_half_date)));

						if($second_half_grace_time < $from_date_time){
							$late_in       = $this->date_differ_fun($second_half_date,$from_date_time);
						}else
						if($second_half_date > $from_date_time){
							$early_in      = $this->date_differ_fun($from_date_time,$second_half_date);
						}
						if($first_half_date < $to_date_time){
							$excess_out    = $this->date_differ_fun($first_half_date,$to_date_time);
						}else
						if($first_half_date > $to_date_time){
							$early_out     = $this->date_differ_fun($to_date_time,$first_half_date);
						}
					}
					//TO CALCULATE A TOTAL EXCESS HOURS BAEED ON PERMISSION SETTING EXCESS HOUR ALLOW INPUT
					if($excess_hr_allow === 1){
						$total_excess_hours = $early_in;
					}else
					if($excess_hr_allow === 2){
						$total_excess_hours = $excess_out;
					}else
					if($excess_hr_allow === 3){
						$total_excess_hours = $early_in + $excess_out;
					}

					//TO CALCULATE A TOTAL LATE HOURS BASED ON  PERMISSION SETTING EARLY GO LATE INPUT
					if($early_go_late === 1){
						$total_late_hours = $late_in + $early_out;
					}else
					if($early_go_late === 2){
						$total_late_hours = $late_in;
					}

					//TO CALCULATE TOTAL WORK HOURS 
					$total_work_hours     = $this->date_differ_fun($from_date_time,$to_date_time);

					if($today === $common_date){
						if($log_date){
							$status     = "false";
							$msg        = "One or More Date(s) Already having in the Punch Details...";  
							break;
						}
					}					
					if($shift_status === 1 || $shift_status === 3 || $shift_status === 2){ //FOR CURRENT IN CURRENT OUT || TOMORROW IN TOMORROW OUT || CURRENT IN TOMORROW OUT
						//if weekoff or unpunch(absent) not check to a same date exist 
						// || $day_type === "FP" || $day_type === "SP"
						if($day_type === "W" || $day_type === "H" || $day_type === "U" || $day_type === "IU" || $day_type === "UI" || $day_type === "FP" || $day_type === "SP" || $day_type === "P"){//weekoff and unpunch and invalid tag only for update
							///CANCELLATION REQUEST NOT WORKING FOR FULL DAY WEEKOFF AND UNPUNCH
							
							if($check_day_type === 1){            
								if($shift_day_type === 1){  //full day
									// echo"$grace_from_time_dte ::: $from_date_time :::$day_type"; die;
										$entry_flag         = "M";
										$whole_day_status   = "M";
										$first_half_status  = "MP";
										$first_half_count   = 0.5;
										$second_half_status = "MP";
										$second_half_count  = 0.5;							
									
									//grace period min and late max min based time FOR FULL DAY BUT CHECK ONLY (1ST HALF) check by DR 5JUL22
									if(($grace_from_time_dte < $from_date_time) && ($day_type === "U" || $day_type === "IU" ||  $day_type === "UI")){
										
											$entry_flag         = "U";
											$update_flag        = "M";
											$whole_day_status   = "IM";
											$first_half_status  = "I";
											$first_half_count   = 0;									
									}
								}else
								if($shift_day_type === 2){ // first half(manual punch)
									if($day_type === "W"){
										$update_flag        = "W";
										$entry_flag         = "M";
										$whole_day_status   = "$entry_flag"."$update_flag";
										$first_half_status  = "MP";
										$first_half_count   = 0.5;
									}else
									if($day_type === "H"){
										$update_flag        = "H";
										$entry_flag         = "M";
										$whole_day_status   = "$entry_flag"."$update_flag";
										$first_half_status  = "MP";
										$first_half_count   = 0.5;
									}else
									if($day_type === "U" || $day_type === "IU" ||  $day_type === "UI"){
										$update_flag        = "U";
										$entry_flag         = "M";
										$whole_day_status   = "$entry_flag"."$update_flag";
										$first_half_status  = "MP";
										$first_half_count   = 0.5;
									}else
									if($day_type === "SP"){  // manual punch request(sh)
										$entry_flag         = "M";
										$update_flag        = "P";
										$whole_day_status   ="$entry_flag". "$update_flag";
										$first_half_status  = "MP";
										$first_half_count   = 0.5;
									}else
									if($day_type === "FP"){   // day type first half and shift day type first half
										$entry_flag         = "M";
										$update_flag        = "U";
										$whole_day_status   ="$entry_flag". "$update_flag";
										$first_half_status  = "MP";
										$first_half_count   = 0.5;
									}else
									if($day_type === "P"){      //wholeday status FP, and shift day type first half
										$entry_flag         = "M";
										$whole_day_status   = "M";
										$first_half_status  = "MP";
										$first_half_count   = 0.5;
										$second_half_status = "MP";
										$second_half_count  = 0.5;	
									}
									//grace period min and lat max min based time FOR 1ST HALF check by DR 5JUL22
									if(($grace_from_time_dte < $from_date_time) && ($day_type === "U" || $day_type === "IU" ||  $day_type === "UI")){
										$entry_flag         = "U";
										$whole_day_status   = "IU";
										$first_half_status  = "I";
										$first_half_count   = 0;
									}
								}else
								if($shift_day_type === 3){  // second half
									if($day_type === "W"){
										$update_flag        = "W";
										$entry_flag         = "M";
										$whole_day_status   = "$update_flag"."$entry_flag";
										$second_half_status = "MP";
										$second_half_count  = 0.5;
									}else
									if($day_type === "H"){
										$update_flag        = "H";
										$entry_flag         = "M";
										$whole_day_status   = "$update_flag"."$entry_flag";
										$second_half_status = "MP";
										$second_half_count  = 0.5;
									}
									else
									if($day_type === "U" || $day_type === "IU" ||  $day_type === "UI"){
										$update_flag        = "U";
										$entry_flag         = "M";
										$whole_day_status   = "$update_flag"."$entry_flag";
										$second_half_status = "MP";
										$second_half_count  = 0.5;
									}else
									if($day_type === "FP"){ //first half present
										$entry_flag         = "P";
										$update_flag        = "M";
										$whole_day_status   = "$entry_flag"."$update_flag";
										$second_half_status = "MP";
										$first_half_count   = 0.5;
									}else
									if($day_type === "SP"){         //Second half preseent, shift day type second half
										$entry_flag         = "U";
										$update_flag        = "M";
										$whole_day_status   ="$entry_flag". "$update_flag";
										$second_half_status = "MP";
										$second_half_count  = 0.5;	
									}else
									if($day_type === "P"){      //wholeday status FP and shift day type first half
										$entry_flag         = "M";
										$whole_day_status   = "M";
										$first_half_status  = "MP";
										$first_half_count   = 0.5;
										$second_half_status = "MP";
										$second_half_count  = 0.5;	
									}
									//grace period min and lat max min based time FOR 2ND HALF check by DR 5JUL22
									if(($grace_second_half_dte < $from_date_time) && ($day_type === "U" || $day_type === "IU" ||  $day_type === "UI")){
										$entry_flag         = "U";
										$whole_day_status   = "UI";
										$second_half_status = "I";
										$second_half_count  = 0;
									}
								}else{
									$status = "false";
									break;
								}
								if($this->control_name === "request" && $leave_status === 1){
									if($can_request === 2){
										//UPD QUERY VALUE
										$time_entry_upd_value .= '("'.$prime_time_id.'","2","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
										// ,"'.$shift_master_id.'"
									}
								}else
								if($this->control_name !== "request"){
									//UPD QUERY VALUE
									$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_master_id.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","3","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
								}
							}
						}else{
							if($check_day_type === 1){								
								if($leave_status === 4){
									$early_in           = 0;
									$late_in            = 0;
									$early_out          = 0;
									$excess_out         = 0;
									$total_work_hours   = 0;
									$total_late_hours   = 0;
									$total_excess_hours = 0;
									if($shift_day_type === 1){
										$entry_flag         = "U";
										$update_flag        = "0";
										$whole_day_status   = "U";
										$first_half_status  = "U";
										$first_half_count   = 0;
										$second_half_status = "U";
										$second_half_count  = 0;
									}else
									if($shift_day_type === 2 || $shift_day_type === 3){
										if($entry_flag  === "M"){
											$entry_flag       = $update_flag;
										}
										//DR CODE FOR INVALID (GRACE TIME AND LATE HR MAX) MANUAL PUNCH CANCEL REQUEST FOR 1ST HALF (5JUL22)
										if($shift_day_type === 2){
											if(($grace_from_time_dte < $from_date_time) && $entry_flag  === "U"){
												$entry_flag       = $update_flag;
											}
										}else
										if($shift_day_type === 3){//DR CODE FOR INVALID (GRACE TIME AND LAT HR MAX) MANUAL PUNCH CANCEL REQUEST FOR 2ND HALF (5JUL22)
											if(($grace_second_half_dte < $from_date_time) && $entry_flag  === "U"){
												$entry_flag       = $update_flag;
											}
										}
										//condition end by DR
										$update_flag         = "U";
										if($shift_day_type === 2){
											$whole_day_status   = $update_flag.$entry_flag;
											$first_half_status  = "U";
											$first_half_count   = 0;
										}else
										if($shift_day_type === 3){
											$whole_day_status   = $entry_flag.$update_flag;
											$second_half_status = "U";
											$second_half_count  = 0;
										}
									}
									$from_date_time      = "0000-00-00 00:00:00";
									$to_date_time        = "0000-00-00 00:00:00";
									//UPD QUERY VALUE
									$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_master_id.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","5","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
								}else{
									$status = "false";
									break;
								}
							}else
							if($check_day_type === 2 || $check_day_type === 3){
								if($leave_status === 4){
									$early_in           = 0;
									$late_in            = 0;
									$early_out          = 0;
									$excess_out         = 0;
									$total_work_hours   = 0;
									$total_late_hours   = 0;
									$total_excess_hours = 0;
									if($check_day_type === 2){
										//DELETE PROCESS FOR INVALID MANUAL PUNCH FOR FULL DAY (BUT CHECK DAY TYPE WAS 2ND HALF)
										if($shift_day_type === 1 && (($grace_from_time_dte < $from_date_time) && $entry_flag  === "U")){
											$from_date_time     = "0000-00-00 00:00:00";
											$to_date_time       = "0000-00-00 00:00:00";
											$entry_flag         = "U";
											$update_flag        = "0";
											$whole_day_status   = "U";
											$first_half_status  = "U";
											$first_half_count   = 0;
											$second_half_status = "U";
											$second_half_count  = 0;
										}else
										if($shift_day_type === 2){
											//DR CODE FOR ENTRY FLAG M OR INVALID (GRACE TIME AND LAT HR MAX) MANUAL PUNCH CANCEL REQUEST FOR 1ST HALF (5JUL22)
											if($entry_flag  === "M" || (($grace_from_time_dte < $from_date_time) && $entry_flag  === "U")){
												$from_date_time  = "0000-00-00 00:00:00";
												$to_date_time    = "0000-00-00 00:00:00";
											}
											$entry_flag         = "U";
											$update_flag        = "0";
											$whole_day_status   = "U";
											$first_half_status  = "U";
											$first_half_count   = 0;
											$second_half_status = "U";
											$second_half_count  = 0;
										}
									}else
									if($check_day_type === 3){
										if($shift_day_type === 1 && (($grace_from_time_dte < $from_date_time) && $entry_flag  === "U")){
											$from_date_time     = "0000-00-00 00:00:00";
											$to_date_time       = "0000-00-00 00:00:00";
											$entry_flag         = "U";
											$update_flag        = "0";
											$whole_day_status   = "U";
											$first_half_status  = "U";
											$first_half_count   = 0;
											$second_half_status = "U";
											$second_half_count  = 0;
										}else
										if($shift_day_type === 3){
											//DR CODE FOR ENTRY FLAG M OR INVALID (GRACE TIME AND LAT HR MAX) MANUAL PUNCH CANCEL REQUEST FOR 2ND HALF (5JUL22)
											if($entry_flag  === "M" || (($grace_second_half_dte < $from_date_time) && $entry_flag  === "U")){
												$from_date_time  = "0000-00-00 00:00:00";
												$to_date_time    = "0000-00-00 00:00:00";
											}
											$entry_flag         = "U";
											$update_flag        = "0";
											$whole_day_status   = "U";
											$first_half_status  = "U";
											$first_half_count   = 0;
											$second_half_status = "U";
											$second_half_count  = 0;
										}
									}
									//UPD QUERY VALUE
									$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_master_id.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","5","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
								}else{
									if($check_day_type === 2){
										if($shift_day_type === 1 || $shift_day_type === 2){
											//THIS CONDITION ONLY FOR PRESENT IN ENTRY FLAG AND BUT WE UPDATE FULL DAY MANUAL PUNCH ENTRY CONCEPT (ALREADY FIRST HALF ADDED)
											if($shift_day_type === 1 && $entry_flag === "P"){
												$entry_flag         = "M";
												$update_flag        = "0";
												$whole_day_status   = "M";
												$first_half_status  = "MP";
												$first_half_count   = 0.5;
												$second_half_status = "MP";
												$second_half_count  = 0.5;
												//grace period min and lat max min based time FOR FULL DAY BUT CHECK ONLY (1ST HALF) TO check by DR 5JUL22
												if($grace_from_time_dte < $from_date_time){
													$entry_flag         = "U";
													$update_flag        = "M";
													$whole_day_status   = "IM";
													$first_half_status  = "I";
													$first_half_count   = 0;
												}
											}else{
												$status = "false";
												break;
											}
										}else//IF ENTRY FLAG WAS P (PRESENT) THEN ONLY ALLOW A MANUAL PUNCH FOR FULL DAY
										if($shift_day_type === 3 && $entry_flag !== "P"){
											$update_flag        = "M";
											$second_half_status = "MP";
											$second_half_count  = 0.5;
											//DR CODE FOR ENTRY FLAG M OR INVALID (GRACE TIME AND LATE HR MAX) MANUAL PUNCH CANCEL REQUEST FOR 2ND HALF (5JUL22)
											if($grace_second_half_dte < $from_date_time){
												$update_flag        = "U";
												$second_half_status = "I";
												$second_half_count  = 0;
											}
											$whole_day_status   = "$entry_flag"."$update_flag";
										}else{
											$status = "false";
											$msg     = "Please Add Only Full Day Manual Punch for this Shift Date..!";
											break;
										}
									}else
									if($check_day_type === 3){
										if($shift_day_type === 1 || $shift_day_type === 3){
											//THIS CONDITION ONLY FOR PRESENT IN ENTRY FLAG AND BUT WE UPDATE FULL DAY MANUAL PUNCH ENTRY CONCEPT (ALREADY FIRST HALF ADDED)
											if($shift_day_type === 1 && $entry_flag === "P"){
												$entry_flag         = "M";
												$update_flag        = "0";
												$whole_day_status   = "M";
												$first_half_status  = "MP";
												$first_half_count   = 0.5;
												$second_half_status = "MP";
												$second_half_count  = 0.5;
												//grace period min and lat max min based time FOR FULL DAY BUT CHECK ONLY (1ST HALF) TO check by DR 5JUL22
												if($grace_from_time_dte < $from_date_time){
													$entry_flag         = "U";
													$update_flag        = "M";
													$whole_day_status   = "IM";
													$first_half_status  = "I";
													$first_half_count   = 0;
												}
											}else{
												$status = "false";
												break;
											}
										}else
										if($shift_day_type === 2 && $entry_flag !== "P"){
											$update_flag        = "M";
											$first_half_status  = "MP";
											$first_half_count   = 0.5;
											//DR CODE FOR ENTRY FLAG M OR INVALID (GRACE TIME AND LAT HR MAX) MANUAL PUNCH CANCEL REQUEST FOR 1ST HALF (5JUL22)
											if($grace_from_time_dte < $from_date_time){
												$update_flag        = "U";
												$first_half_status = "I";
												$second_half_count  = 0;
											}
											$whole_day_status   = "$update_flag"."$entry_flag";
										}else{
											$status = "false";
											$msg    = "Please Add Only Full Day Manual Punch for this Shift Date..!";
											break;
										}
									}
									if($this->control_name === "request" && $leave_status === 1){
										if($can_request === 2){
											//UPD QUERY VALUE
											$time_entry_upd_value .= '("'.$prime_time_id.'","2","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
											// ,"'.$shift_master_id.'"
										}
									}else
									if($this->control_name !== "request"){
										//UPD QUERY VALUE
										$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_master_id.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","3","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
									}
								}
							}else{
								if($shift_day_type === 1){
									$entry_flag         = "M";
									$update_flag        = "0";
									$whole_day_status   = "M";
									$first_half_status  = "MP";
									$first_half_count   = 0.5;
									$second_half_status = "MP";
									$second_half_count  = 0.5;
									//grace period min and lat max min based time FOR FULL DAY BUT CHECK ONLY (1ST HALF) TO check by DR 5JUL22
									if($grace_from_time_dte < $from_date_time){
										$entry_flag         = "U";
										$update_flag        = "M";
										$whole_day_status   = "IM";
										$first_half_status  = "I";
										$first_half_count   = 0;
									}
								}else
								if($shift_day_type === 2){
									$entry_flag         = "M";
									$update_flag        = "0";
									$whole_day_status   = "FM";
									$first_half_status  = "MP";
									$first_half_count   = 0.5;
									//grace period min and lat max min based time CHECK FOR (1ST HALF) TO check by DR 5JUL22
									if($grace_from_time_dte < $from_date_time){
										$entry_flag         = "U";
										$update_flag        = "U";
										$whole_day_status   = "IU";
										$first_half_status  = "I";
										$first_half_count   = 0;
										$second_half_status = "U";
										$second_half_count  = 0;
									}
								}else
								if($shift_day_type === 3){
									$entry_flag         = "M";
									$update_flag        = "0";
									$whole_day_status   = "SM";
									$second_half_status = "MP";
									$second_half_count  = 0.5;
									//grace period min and lat max min based time FOR 2ND HALF check by DR 5JUL22
									if($grace_second_half_dte < $from_date_time){
										$entry_flag         = "U";
										$update_flag        = "U";
										$whole_day_status   = "UI";
										$second_half_status = "I";
										$second_half_count  = 0;
										$first_half_status  = "U";
										$first_half_count   = 0;
									}
								}else{
									$status = "false";
									break;
								}
								if($this->control_name === "request" && $leave_status === 1){
									if($can_request === 2){
										$time_entry_ins_value .= '("'.$employee_code.'","'.$shift_master_id.'","'.$common_date.'","U","U","2","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
									}
								}else
								if($this->control_name !== "request"){
									//FOR DIRECT LEAVE ENTRY
									if($this->control_name !== "approval"){
										$time_entry_ins_value .= '("'.$employee_code.'","'.$shift_master_id.'","'.$common_date.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","3","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
									}else{//FOR APPROVAL
										$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_master_id.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","3","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
									}
								}
							}
						}
					}
				}else
				if($request_type === 1 || $request_type === 3 || $request_type === 8){
					$full_present_arr = array("PU","UP","P","FP","SP","IP","PI"); //Ef - L,O --- Up -P
					$fh_present_arr   = array("PL","PO","PM"); //EF - L,O  --- UF - 
					$sh_present_arr   = array("LP","OP","MP"); //EF - P
					//if weekoff or unpunch(absent) not check to same date exist 
					if($key === 0){ 
						if($day_type === "W" || $day_type === "H" || $day_type === "U" || $day_type === "IU" || $day_type === "UI" || in_array($day_type, $full_present_arr)){//weekoff and unpunch and invalid tag only for update
							if($check_day_type === 1){
								if($from_date_type === 1){    //FULL DAY - from request Module
									if($request_type === 1){
										$entry_flag         = "L";
										$whole_day_status   = "L";
										$first_half_status  = $leave_name;
										$second_half_status = $leave_name;
									}else
									if($request_type === 3 || $request_type === 8){
										$entry_flag         = "O";
										// $update_flag        = "O";
										$whole_day_status   = "O";
										$first_half_status  = "O";
										$second_half_status = "O";
									}
									$first_half_count   = 0.5;
									$second_half_count  = 0.5;
								}else
								if($from_date_type === 2){   // 1ST HALF from request
									if(in_array($day_type, $full_present_arr)){
										
										if($request_type === 1){
											$update_flag  = "P";
											if($day_type === "FP"){
												$entry_flag         = "L";
												$update_flag        = "U";
												$first_half_status  = $leave_name;
												$whole_day_status   = "$entry_flag"."$update_flag";
												$first_half_count   = 0.5;
											}else{
												$entry_flag         = "L";
												$first_half_status  = $leave_name;
												$whole_day_status   = "$entry_flag"."$update_flag";
												$first_half_count   = 0.5;
											}											
										}else
										if($request_type === 3 || $request_type === 8){
											if($day_type === "FP"){
												$entry_flag         = "O";
												$update_flag        = "U";
												$first_half_status  = "O";
												$whole_day_status   = "$entry_flag"."$update_flag";
												$first_half_count   = 0.5;
											}else
											if($day_type === "SP" || $day_type === "P"){
												$update_flag        = $entry_flag;
												$entry_flag         = "O";												
												$first_half_status  = "O";
												$whole_day_status   = "$entry_flag"."$update_flag";
												$first_half_count   = 0.5;
											}else{
												$entry_flag         = "O";
												$first_half_status  = "O";
												$whole_day_status   = "$entry_flag"."$update_flag";
												$first_half_count   = 0.5;
											}											
										}
										
									}else
									if(in_array($day_type, $fh_present_arr)){
										//$update_flag  = "P";
										if($request_type === 1){
											$entry_flag        = "L";
											$first_half_status = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$entry_flag        = "O";
											$first_half_status = "O";
										}
										$whole_day_status   = "$entry_flag"."$update_flag";
										$first_half_count   = 0.5;
									}else									
									if($day_type === "W"){
										$update_flag  = "W";
										if($request_type === 1){
											$entry_flag        = "L";
											$first_half_status = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$entry_flag        = "O";
											$first_half_status = "O";
										}
										$whole_day_status   = "$entry_flag"."$update_flag";
										$first_half_count   = 0.5;
									}else
									if($day_type === "H"){
										$update_flag  = "H";
										if($request_type === 1){
											$entry_flag        = "L";
											$first_half_status = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$entry_flag        = "O";
											$first_half_status = "O";
										}
										$whole_day_status   = "$entry_flag"."$update_flag";
										$first_half_count   = 0.5;
									}else
									if($day_type === "U" || $day_type === "IU" || $day_type === "UI" ){
										$update_flag  = "U";
										if($request_type === 1){
											$entry_flag         = "L";
											$first_half_status  = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$entry_flag         = "O";
											$first_half_status  = "O";
										}
										//FOR INVALID DATA
										if($day_type === "UI"){
											$whole_day_status   = "$entry_flag"."I";
										}else{
											$whole_day_status   = "$entry_flag"."$update_flag";
										}
										$first_half_count   = 0.5;
									}
								}else
								if($from_date_type === 3){     // 2ND HALF from request
									if(in_array($day_type, $full_present_arr)){
										//$update_flag  = "P";
										if($request_type === 1){
											if($day_type === "SP"){
												$entry_flag         = "U";
												$update_flag        = "L"; 
												$second_half_status = $leave_name;  
												$whole_day_status   = "$entry_flag"."$update_flag";
												$first_half_count   = 0.5;
											}else{
												$update_flag        = "L";
												$second_half_status  = $leave_name;
												$whole_day_status   = "$entry_flag"."$update_flag";
												$second_half_count   = 0.5;
											}											
										}else
										if($request_type === 3 || $request_type === 8){
											if($day_type === "SP"){
												$entry_flag          = "U";
												$update_flag         = "O";
												$second_half_status  = "O";
												$whole_day_status    = "$entry_flag"."$update_flag";
												$second_half_count    = 0.5;
											}else{
												$update_flag         = "O";
												$second_half_status  = "O";
												$whole_day_status    = "$entry_flag"."$update_flag";
												$second_half_count   = 0.5;
											}											
										}
									}else
									if(in_array($day_type, $sh_present_arr)){
										//$update_flag  = "P";
										if($request_type === 1){
											$update_flag        = "L";
											$first_half_status = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$update_flag        = "O";
											$first_half_status = "O";
										}
										$whole_day_status   = "$entry_flag"."$update_flag";
										$first_half_count   = 0.5;
									}else
									if($day_type === "W"){
										// $update_flag  = "W";
										if($request_type === 1){
											$update_flag        = "L";
											$second_half_status = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$update_flag        = "O";
											$second_half_status = "O";
										}				
											$whole_day_status   = "$entry_flag"."$update_flag";						
											$second_half_count  = 0.5;
									}else
									if($day_type === "H"){
										// $update_flag  = "H";
										if($request_type === 1){
											$update_flag        = "L";
											$second_half_status = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$update_flag         = "O";
											$second_half_status = "O";
										}
										$whole_day_status   = "$entry_flag"."$update_flag";
										$second_half_count  = 0.5;
									}else
									if($day_type === "U" || $day_type === "IU" || $day_type === "UI"){
										
										if($request_type === 1){
											$update_flag        = "L";
											$second_half_status = $leave_name;
											$whole_day_status   = "$entry_flag"."$update_flag";
										}else{
											$update_flag  = "U";
											if($request_type === 3 || $request_type === 8){
												$entry_flag         = "O";
												$second_half_status = "O";
											}
											//FOR INVALID DATA
											if($day_type === "IU"){
												$whole_day_status   = "I"."$entry_flag";
											}else{
												$whole_day_status   = "$update_flag"."$entry_flag";
											}
										}
										$second_half_count  = 0.5;
									}
								}else{
									$status = "false";
									break;
								}
								if($this->control_name === "request" && $leave_status === 1){
									if($can_request === 2){
										//UPD QUERY VALUE
										$time_entry_upd_value .= '("'.$prime_time_id.'","2","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
										// ,"'.$shift_master_id.'"
									}
								}else
								if($this->control_name !== "request"){
									//UPD QUERY VALUE
									$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_master_id.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","3","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
								}
							}
						}else
						if($check_day_type === 1 || $check_day_type === $from_date_type){
							if($leave_status === 4){
								if($from_date_type === 1){
									$entry_flag         = "U";
									$update_flag        = "0";
									$whole_day_status   = "U";
									$first_half_status  = "U";
									$first_half_count   = 0;
									$second_half_status = "U";
									$second_half_count  = 0;
								}else
								if($from_date_type === 2 || $from_date_type === 3){
									//if only request should be full day and whole day status should be full day
									if($check_day_type === 1){
										if($request_type === 1){
											if($entry_flag  === "L"){
												$entry_flag    = $update_flag;	
											}
										}else
										if($request_type === 3 || $request_type === 8){
											if($entry_flag  === "O"){
												$entry_flag    = $update_flag;
											}
										}
										$update_flag   = "U";
										if($from_date_type === 2){
											$whole_day_status   = $update_flag.$entry_flag;
											$first_half_status  = "U";
											$first_half_count   = 0;
										}else
										if($from_date_type === 3){
											$whole_day_status   = $entry_flag.$update_flag;
											$second_half_status = "U";
											$second_half_count  = 0;
										}
									}else{
										$entry_flag         = "U";
										$update_flag        = "0";
										$first_half_status  = "U";
										$first_half_count   = 0;
										$second_half_status = "U";
										$second_half_count  = 0;
										if($whole_day_status === "LI"){
											if($from_date_type === 2){
												$update_flag        = "U";
												$whole_day_status   = "UI";
												$second_half_status = "I";
												$second_half_count  = 0;
											}
										}else
										if($whole_day_status === "IL"){
											if($from_date_type === 3){
												$update_flag        = "U";
												$whole_day_status   = "IU";
												$first_half_status  = "I";
												$first_half_count   = 0;
											}
										}else{
											$whole_day_status   = "U";
										}
									}
								}
								//UPD QUERY VALUE
								$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_master_id.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","5","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
							}else{
								$status = "false";
								break;				
							}
							
						}else
						if(($check_day_type !== $from_date_type) && $entry_flag){
							if($from_date_type === 1){
								$status = "false";
								break;
							}else{															
								if($request_type === 1){
									if(in_array($day_type, $fh_present_arr) || in_array($day_type, $sh_present_arr)){ //Only for Present Modify
										if($entry_flag === 'P'){
											$entry_flag = "L";
										}else
										if($update_flag === 'P'){
											$update_flag = "L";
										}
									}else{
										$update_flag  = "L";
									}									
								}else
								if($request_type === 3 || $request_type === 8){
									if(in_array($day_type, $fh_present_arr) || in_array($day_type, $sh_present_arr)){ //Only for Present Modify
										if($entry_flag === 'P'){
											$entry_flag = "O";
											
										}else
										if($update_flag === 'P'){
											$update_flag = "O";
										}
									}else{
										$update_flag  = "O";
									}										
								}								
								//for 1st half update
								if($check_day_type === 3){
									if($from_date_type === 2){
										if($request_type === 1){
											$first_half_status  = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$first_half_status  = "O";
										}
										if(in_array($day_type, $fh_present_arr)){
											$whole_day_status   = "$entry_flag"."$update_flag";
										}else{
											$whole_day_status   = "$update_flag"."$entry_flag";
										}
										$first_half_count   = 0.5;
									}
								}
								//for 2nd half update
								else
								if($check_day_type === 2){
									if($from_date_type === 3){
										if($request_type === 1){
											$second_half_status = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$second_half_status = "O";
										}
										$whole_day_status   = "$entry_flag"."$update_flag";
										$second_half_count  = 0.5;
									}
								}
								if($this->control_name === "request" && $leave_status === 1){
									if($can_request === 2){
										//UPD QUERY VALUE
										$time_entry_upd_value .= '("'.$prime_time_id.'","2","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
										// ,"'.$shift_master_id.'"
									}
								}else
								if($this->control_name !== "request"){
									//UPD QUERY VALUE
									$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_master_id.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","3","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
								}
							}
							
						}else{
							//for full day insert
							if($from_date_type === 1){
								if($request_type === 1){
									$whole_day_status   = "L";
									$first_half_status  = $leave_name;
									$second_half_status = $leave_name;
								}else
								if($request_type === 3 || $request_type === 8){
									$whole_day_status   = "O";
									$first_half_status  = "O";
									$second_half_status = "O";
								}
								$first_half_count   = 0.5;
								$second_half_count  = 0.5;
							}else//for 1st half insert
							if($from_date_type === 2){
								if($request_type === 1){
									$whole_day_status   = "FL";
									$first_half_status  = $leave_name;
								}else
								if($request_type === 3 || $request_type === 8){
									$whole_day_status   = "FO";
									$first_half_status  = "O";
								}
								$first_half_count   = 0.5;
							}else//for 2nd half insert
							if($from_date_type === 3){
								if($request_type === 1){
									$whole_day_status   = "SL";
									$second_half_status = $leave_name;
								}else
								if($request_type === 3 || $request_type === 8){
									$whole_day_status   = "SO";
									$second_half_status = "O";
								}
								$second_half_count  = 0.5;
							}
							if($request_type === 1){
								$entry_flag     = "L";
							}else
							if($request_type === 3 || $request_type === 8){
								$entry_flag     = "O";
							}
							if($this->control_name === "request" && $leave_status === 1){
								if($can_request === 2){
									$time_entry_ins_value .= '("'.$employee_code.'","'.$shift_master_id.'","'.$common_date.'","U","U","2","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
								}
							}else
							if($this->control_name !== "request"){
								//FOR DIRECT LEAVE ENTRY
								if($this->control_name !== "approval"){
									//INSERT QUERY VALUE
									$time_entry_ins_value .= '("'.$employee_code.'","'.$shift_master_id.'","'.$common_date.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","3","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
								//FOR APPROVAL
								}else{
									$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_master_id.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","3","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
								}
							}
						}
					}else
					if($key === $end_key){
						if($day_type === "W" || $day_type === "H" || $day_type === "U" || $day_type === "IU" || $day_type === "UI" || in_array($day_type, $full_present_arr)){//weekoff and unpunch and invalid tag only for update
							if($check_day_type === 1){
								if($to_date_type === 1){
									if($request_type === 1){
										$entry_flag         = "L";
										$whole_day_status   = "L";
										$first_half_status  = $leave_name;
										$second_half_status = $leave_name;
									}else
									if($request_type === 3 || $request_type === 8){
										$entry_flag         = "O";
										$whole_day_status   = "O";
										$first_half_status  = "O";
										$second_half_status = "O";
									}
									$first_half_count   = 0.5;
									$second_half_count  = 0.5;
								}else
								if($to_date_type === 2){
									if(in_array($day_type, $full_present_arr)){
										$update_flag  = "P";
										if($request_type === 1){
											$entry_flag        = "L";
											$first_half_status = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$entry_flag        = "O";
											$first_half_status = "O";
										}
										$whole_day_status   = "$entry_flag"."$update_flag";
										$first_half_count   = 0.5;
									}else
									if(in_array($day_type, $fh_present_arr)){
										//$update_flag  = "P";
										if($request_type === 1){
											$entry_flag        = "L";
											$first_half_status = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$entry_flag        = "O";
											$first_half_status = "O";
										}
										$whole_day_status   = "$entry_flag"."$update_flag";
										$first_half_count   = 0.5;
									}else
									if($day_type === "W"){
										$update_flag  = "W";
										if($request_type === 1){
											$entry_flag         = "L";
											$first_half_status  = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$entry_flag         = "O";
											$first_half_status  = "O";
										}
										$whole_day_status   = "$entry_flag"."$update_flag";
										$first_half_count   = 0.5;
									}else
									if($day_type === "H"){
										$update_flag  = "H";
										if($request_type === 1){
											$entry_flag         = "L";
											$first_half_status  = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$entry_flag         = "O";
											$first_half_status  = "O";
										}
										$whole_day_status   = "$entry_flag"."$update_flag";
										$first_half_count   = 0.5;
									}else
									if($day_type === "U" || $day_type === "IU" || $day_type === "UI"){
										$update_flag  = "U";
										if($request_type === 1){
											$entry_flag         = "L";
											$first_half_status  = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$entry_flag         = "O";
											$first_half_status  = "O";
										}
										//FOR INVALID DATA
										if($day_type === "UI"){
											$whole_day_status   = "$entry_flag"."I";
										}else{
											$whole_day_status   = "$entry_flag"."$update_flag";
										}
										$first_half_count   = 0.5;
									}
								}else
								if($to_date_type === 3){
									if(in_array($day_type, $fh_present_arr)){
										//$update_flag  = "P";
										if($request_type === 1){
											$update_flag        = "L";
											$first_half_status = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$update_flag        = "O";
											$first_half_status = "O";
										}
										$whole_day_status   = "$entry_flag"."$update_flag";
										$first_half_count   = 0.5;
									}else
									if(in_array($day_type, $sh_present_arr)){ 
										//$update_flag  = "P";
										if($request_type === 1){
											$update_flag        = "L";
											$first_half_status = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$update_flag        = "O";
											$first_half_status = "O";
										}
										$whole_day_status   = "$entry_flag"."$update_flag";
										$first_half_count   = 0.5;
									}else
									if($day_type === "W"){
										$update_flag  = "W";
										if($request_type === 1){
											$entry_flag         = $update_flag;
											$update_flag        = "L";
											$second_half_status = $leave_name;
											
										}else
										if($request_type === 3 || $request_type === 8){
											$update_flag        = $entry_flag;
											$entry_flag         = "O";
											$second_half_status = "O";
										}
										$whole_day_status   =  "$entry_flag"."$update_flag";
										$second_half_count  = 0.5;
									}else
									if($day_type === "H"){
										$update_flag  = "H";
										if($request_type === 1){
											$entry_flag         = "L";
											$second_half_status = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$entry_flag         = "O";
											$second_half_status = "O";
										}
										$whole_day_status   = "$update_flag"."$entry_flag";
										$second_half_count  = 0.5;
									}else
									if($day_type === "U" || $day_type === "IU" || $day_type === "UI"){
										$update_flag  = "U";
										if($request_type === 1){
											$entry_flag         = "L";
											$second_half_status = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$entry_flag         = "O";
											$second_half_status = "O";
										}
										//FOR INVALID DATA
										if($day_type === "IU"){
											$whole_day_status   = "I"."$entry_flag";
										}else{
											$whole_day_status   = "$update_flag"."$entry_flag";
										}
										$second_half_count  = 0.5;
									}
								}else{
									$status = "false";
									break;
								}
								if($this->control_name === "request" && $leave_status === 1){
									if($can_request === 2){
										//UPD QUERY VALUE
										$time_entry_upd_value .= '("'.$prime_time_id.'","2","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
										// ,"'.$shift_master_id.'"
									}
								}else
								if($this->control_name !== "request"){
									//UPD QUERY VALUE
									$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_master_id.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","3","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
								}
							}
						}else
						if($check_day_type === 1 || $check_day_type === $to_date_type){
							if($leave_status === 4){
									if($to_date_type === 1){
										$entry_flag         = "U";
										$update_flag        = "0";
										$whole_day_status   = "U";
										$first_half_status  = "U";
										$first_half_count   = 0;
										$second_half_status = "U";
										$second_half_count  = 0;
									}else
									if($to_date_type === 2 || $to_date_type === 3){
										//if only request should be full day and whole day status should be full day
										if($check_day_type === 1){
											if($request_type === 1){
												if($entry_flag  === "L"){
													$entry_flag    = $update_flag;	
												}
											}else
											if($request_type === 3 || $request_type === 8){
												if($entry_flag  === "O"){
													$entry_flag    = $update_flag;
												}
											}
											$update_flag   = "U";
											if($to_date_type === 2){
												$whole_day_status   = $update_flag.$entry_flag;
												$first_half_status  = "U";
												$first_half_count   = 0;
											}else
											if($to_date_type === 3){
												$whole_day_status   = $entry_flag.$update_flag;
												$second_half_status = "U";
												$second_half_count  = 0;
											}
										}else{
											$entry_flag         = "U";
											$update_flag        = "0";
											$first_half_status  = "U";
											$first_half_count   = 0;
											$second_half_status = "U";
											$second_half_count  = 0;
											if($whole_day_status === "LI"){
												if($to_date_type === 2){
													$update_flag        = "U";
													$whole_day_status   = "UI";
													$second_half_status = "I";
													$second_half_count  = 0;
												}
											}else
											if($whole_day_status === "IL"){
												if($to_date_type === 3){
													$update_flag        = "U";
													$whole_day_status   = "IU";
													$first_half_status  = "I";
													$first_half_count   = 0;
												}
											}else{
												$whole_day_status   = "U";
											}
										}
									}
								// }
								//UPD QUERY VALUE
								$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_master_id.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","5","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
							}else{
								$status = "false";	
								break;
								
							}
						}else
						if(($check_day_type !== $to_date_type) && $entry_flag){
							if($to_date_type === 1){
								$status = "false";
								break;
							}else{
								if($request_type === 1){
									$update_flag  = "L";
								}else
								if($request_type === 3 || $request_type === 8){
									$update_flag  = "O";
								}
								//for 1st half update
								if($check_day_type === 3){
									if($to_date_type === 2){
										if($request_type === 1){
											$first_half_status  = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$first_half_status  = "O";
										}
										$whole_day_status   = "$update_flag"."$entry_flag";
										$first_half_count   = 0.5;
									}
								}
								//for 2nd half update
								else
								if($check_day_type === 2){
									if($to_date_type === 3){
										if($request_type === 1){
											$second_half_status = $leave_name;
										}else
										if($request_type === 3 || $request_type === 8){
											$second_half_status = "O";
										}
										$whole_day_status   = "$entry_flag"."$update_flag";
										$second_half_count  = 0.5;
									}
								}
								if($this->control_name === "request" && $leave_status === 1){
									if($can_request === 2){
										//UPD QUERY VALUE
										$time_entry_upd_value .= '("'.$prime_time_id.'","2","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
										// ,"'.$shift_master_id.'"
									}
								}else
								if($this->control_name !== "request"){
									//UPD QUERY VALUE
									$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_master_id.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","3","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
								}
							}
						}else{//for full day insert
							if($to_date_type === 1){
								if($request_type === 1){
									$whole_day_status   = "L";
									$first_half_status  = $leave_name;
									$second_half_status = $leave_name;
								}else
								if($request_type === 3 || $request_type === 8){
									$whole_day_status   = "O";
									$first_half_status  = "O";
									$second_half_status = "O";
								}
								$first_half_count   = 0.5;
								$second_half_count  = 0.5;
							}
							else//for 1st half insert
							if($to_date_type === 2){
								if($request_type === 1){
									$whole_day_status   = "FL";
									$first_half_status  = $leave_name;
								}else
								if($request_type === 3 || $request_type === 8){
									$whole_day_status   = "FO";
									$first_half_status  = "O";
								}
								$first_half_count   = 0.5;
								$second_half_status = "";
								$second_half_count  = "";
							}
							else//for 2nd half insert
							if($to_date_type === 3){
								if($request_type === 1){
									$whole_day_status   = "SL";
									$second_half_status = $leave_name;
								}else
								if($request_type === 3 || $request_type === 8){
									$whole_day_status   = "SO";
									$second_half_status = "O";
								}
								$first_half_status  = "";
								$first_half_count   = "";
								$second_half_count  = 0.5;
							}
							if($request_type === 1){
								$entry_flag     = "L";
							}else
							if($request_type === 3 || $request_type === 8){
								$entry_flag     = "O";
							}
							if($this->control_name === "request" && $leave_status === 1){
								if($can_request === 2){
									$time_entry_ins_value .= '("'.$employee_code.'","'.$shift_master_id.'","'.$common_date.'","U","U","2","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
								}
							}else
							if($this->control_name !== "request"){
								//FOR DIRECT LEAVE ENTRY
								if($this->control_name !== "approval"){
								//INSERT QUERY VALUE
									$time_entry_ins_value .= '("'.$employee_code.'","'.$shift_master_id.'","'.$common_date.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","3","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
								}else{//FOR APPROVAL
									$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_master_id.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","3","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
								}
							}
						}	
					}else{//this conddition only valid for more than 2 days choose from request 
						if($day_type === "W" || $day_type === "H" || $day_type === "U" || $day_type === "IU" || $day_type === "UI" || in_array($day_type, $full_present_arr)){//weekoff and unpunch and invalid tag only for update
							if($check_day_type === 1){
								if($request_type === 1){
									$entry_flag         = "L";
									$whole_day_status   = "L";
									$first_half_status  = $leave_name;
									$second_half_status = $leave_name;
								}else
								if($request_type === 3 || $request_type === 8){
									$entry_flag         = "O";
									$whole_day_status   = "O";
									$first_half_status  = "O";
									$second_half_status = "O";
								}
								$first_half_count   = 0.5;
								$second_half_count  = 0.5;
								if($this->control_name === "request" && $leave_status === 1){
									if($can_request === 2){
										//UPD QUERY VALUE
										$time_entry_upd_value .= '("'.$prime_time_id.'","2","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
										// ,"'.$shift_master_id.'"
									}
								}else
								if($this->control_name !== "request"){
									//UPD QUERY VALUE
									$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_master_id.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","3","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
								}
							}
						}else//this condition only valid for more than 2 days choose from request 
						if($check_day_type === 1 || $check_day_type === 2 || $check_day_type === 3){
							if($leave_status === 4){
								$entry_flag         = "U";
								$update_flag        = "0";
								$whole_day_status   = "U";
								$first_half_status  = "U";
								$first_half_count   = 0;
								$second_half_status = "U";
								$second_half_count  = 0;

								//UPD QUERY VALUE
								$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_master_id.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","5","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
							}else{
								$status = "false";
								break;
							}
						}else{//check leave days for intervening type third
							if((int)$weekoff_value === 0 || (in_array("3",$intervening_type) && ((int)$weekoff_value || $get_common_holiday))){
								if($request_type === 1){
									$whole_day_status   = "L";
									$first_half_status  = $leave_name;
									$second_half_status = $leave_name;
								}else
								if($request_type === 3 || $request_type === 8){
									$whole_day_status   = "O";
									$first_half_status  = "O";
									$second_half_status = "O";
								}
								$first_half_count   = 0.5;
								$second_half_count  = 0.5;
								$ins_upd_rslt       = 1;
								
							}else
							if((int)$weekoff_value === 3 && ($intervening_holidays !== 1 && !$get_common_holiday)){
								if($request_type === 1){
									$whole_day_status   = "FL";
									$first_half_status  = $leave_name;
								}else
								if($request_type === 3 || $request_type === 8){
									$whole_day_status   = "FO";
									$first_half_status  = "O";
								}
								$first_half_count   = 0.5;
								$ins_upd_rslt       = 1;

							}else
							if((int)$weekoff_value === 2 && ($intervening_holidays !== 1 && !$get_common_holiday)){
								if($request_type === 1){
									$whole_day_status   = "SL";
									$second_half_status = $leave_name;
								}else
								if($request_type === 3 || $request_type === 8){
									$whole_day_status   = "SO";
									$second_half_status = "O";
								}
								$second_half_count  = 0.5;
								$ins_upd_rslt       = 1;
								
							}else{
								//IF LEAVE COUNT IS 0 SO NOT INSERT OR UPDATE TO TIME ENTRY
								$ins_upd_rslt = 0;
							}	
							if($request_type === 1){
								$entry_flag     = "L";
							}else
							if($request_type === 3 || $request_type === 8){
								$entry_flag     = "O";
							}
					
							//INSERT QUERY VALUE
							if($ins_upd_rslt){
								if($this->control_name === "request" && $leave_status === 1){
									if($can_request === 2){
										$time_entry_ins_value .= '("'.$employee_code.'","'.$shift_master_id.'","'.$common_date.'","U","U","2","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
									}
								}else
								if($this->control_name !== "request"){
									//FOR DIRECT LEAVE ENTRY
									if($this->control_name !== "approval"){
										$time_entry_ins_value .= '("'.$employee_code.'","'.$shift_master_id.'","'.$common_date.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","3","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
									}else{//FOR APPROVAL
										$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_master_id.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","3","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
									}	
								}
							}
						}
					}
				}
			}
		}
		if($status === "true"){
			$time_entry_upd_info      = "";
			$time_entry_ins_info      = "";
			if($this->control_name !== "request"){
				//FOR APPROVAL MODULE REJECTED ENTRY UPDATE QUERY
				if($this->control_name === "approval" && $leave_status === 3){
					if($time_entry_upd_value){
						$time_entry_upd_value   = rtrim($time_entry_upd_value,",");
						//TIME ENTRY UPD QUERY
						$time_entry_upd_qry     = 'INSERT INTO cw_time_entry (prime_time_entry_id,action_status,trans_updated_by,trans_updated_date) VALUES '.$time_entry_upd_value.' ON DUPLICATE KEY UPDATE action_status = VALUES(action_status),trans_updated_by = VALUES(trans_updated_by),trans_updated_date = VALUES(trans_updated_date)';
						// ,shift_id
						// UPDATE shift_id = VALUES(shift_id),
						$time_entry_upd_info    = $this->db->query("CALL sp_a_run ('RUN','$time_entry_upd_qry')");
					}
				}else{
					if($time_entry_upd_value){
						$time_entry_upd_value   = rtrim($time_entry_upd_value,",");
						//TIME ENTRY UPD QUERY
						$time_entry_upd_qry     = 'INSERT INTO cw_time_entry (prime_time_entry_id,shift_id,early_in,late_in,early_out,excess_out,total_work_hours,total_late_hours,total_excess_hours,entry_flag,update_flag,whole_day_status,manual_in,manual_out,first_half_status,first_half_count,second_half_status,second_half_count,action_status,trans_updated_by,trans_updated_date) VALUES '.$time_entry_upd_value.' ON DUPLICATE KEY UPDATE shift_id = VALUES(shift_id),early_in = VALUES(early_in),late_in = VALUES(late_in),early_out = VALUES(early_out),excess_out = VALUES(excess_out),total_work_hours = VALUES(total_work_hours),total_late_hours = VALUES(total_late_hours),total_excess_hours = VALUES(total_excess_hours),entry_flag = VALUES(entry_flag),update_flag = VALUES(update_flag),whole_day_status = VALUES(whole_day_status),manual_in = VALUES(manual_in),manual_out = VALUES(manual_out),first_half_status = VALUES(first_half_status),first_half_count = VALUES(first_half_count),second_half_status = VALUES(second_half_status),second_half_count = VALUES(second_half_count),action_status = VALUES(action_status),trans_updated_by = VALUES(trans_updated_by),trans_updated_date = VALUES(trans_updated_date)';
						$time_entry_upd_info   = $this->db->query("CALL sp_a_run ('INSERT','$time_entry_upd_qry')");
						$time_entry_upd_rslt   = $time_entry_upd_info->result();
						$time_entry_upd_info->next_result();
						
						if((int)$leave_status === 4){
							if((int)$request_type === 6 || (int)$request_type === 7){
								$from_date       = date("Y-m-d",strtotime($shift_date));
								$to_date         = date("Y-m-d",strtotime($shift_date));
							}else{
								$from_date       = $from_date;
								$to_date         = $to_date;
							}
							/*$qry_info          = $this->db->query("CALL itsp_prcatt ('$from_date','$to_date','$employee_code')");
							$qry_result        = $qry_info->result();
							$qry_info->next_result();*/
						}
						
					}		
					//TIME ENTRY INSERT QUERY
					if($time_entry_ins_value){
						$time_entry_ins_value   = rtrim($time_entry_ins_value,",");
						$time_entry_ins_qry     = 'INSERT INTO cw_time_entry (employee_code,shift_id,att_date,early_in,late_in,early_out,excess_out,total_work_hours,total_late_hours,total_excess_hours,entry_flag,update_flag,whole_day_status,manual_in,manual_out,first_half_status,first_half_count,second_half_status,second_half_count,action_status,trans_created_by,trans_created_date) VALUES '.$time_entry_ins_value.'';
						$time_entry_ins_info    = $this->db->query("CALL sp_a_run ('RUN','$time_entry_ins_qry')");
					}
				}
				if($time_entry_upd_info || $time_entry_ins_info){
					return array('success' => "true", 'message' => 'proceed');
				}
			}else{//FOR REQUEST
				if($time_entry_upd_value){
					$time_entry_upd_value   = rtrim($time_entry_upd_value,",");
					//TIME ENTRY UPD QUERY
					$time_entry_upd_qry     = 'INSERT INTO cw_time_entry (prime_time_entry_id,action_status,trans_updated_by,trans_updated_date) VALUES '.$time_entry_upd_value.' ON DUPLICATE KEY UPDATE action_status = VALUES(action_status),trans_updated_by = VALUES(trans_updated_by),trans_updated_date = VALUES(trans_updated_date)';
					// ,shift_id
					// UPDATE shift_id = VALUES(shift_id),
					$time_entry_upd_info    = $this->db->query("CALL sp_a_run ('RUN','$time_entry_upd_qry')");
				}
				//TIME ENTRY INSERT QUERY
				if($time_entry_ins_value){
					$time_entry_ins_value   = rtrim($time_entry_ins_value,",");
					$time_entry_ins_qry     = 'INSERT INTO cw_time_entry (employee_code,shift_id,att_date,entry_flag,whole_day_status,action_status,trans_created_by,trans_created_date) VALUES '.$time_entry_ins_value.'';
					$time_entry_ins_info    = $this->db->query("CALL sp_a_run ('RUN','$time_entry_ins_qry')");
				}
				return array('success' => "true", 'message' => 'proceed');
			}
		}else{
			return array('success' => "false", 'message' => $msg);
		}
	}
	
	//Get Last Payroll Month date
	public function get_last_payroll_month($category){
		//GET A EMPLOYEE CODE AND PROCESS MONTH FORM LEAVE EXPORT MODULE
		$payroll_posting_query  = 'SELECT role as category,date_format(MAX(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y")) , "%m-%Y") AS process_month from cw_transactions where cw_transactions.role ="'.$category.'" and cw_transactions.trans_status = 1';			
		$payroll_posting_info   = $this->db->query("CALL sp_a_run ('SELECT','$payroll_posting_query')");
        $payroll_posting_result = $payroll_posting_info->result();
        $payroll_posting_info->next_result();
        $process_month          =  $payroll_posting_result[0]->process_month;
        return $process_month;
	}
	public function get_last_transaction($category){
		$payroll_query  = 'SELECT max(date_format(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y") , "%Y-%m")) as transactions_month FROM cw_transactions WHERE role = "'.$category.'" and trans_status =1 ORDER BY `prime_transactions_id` DESC';
		$payroll_info   = $this->db->query("CALL sp_a_run ('SELECT','$payroll_query')");
		$payroll_rslt   = $payroll_info->result();
		$payroll_info->next_result();
		$trans_last_month 	  = $payroll_rslt[0]->transactions_month;
		if($trans_last_month){
			$trans_last_month = $trans_last_month."-01";
			$trans_last_month = date('m-Y', strtotime('+1 month', strtotime($trans_last_month)));
		}
		return $trans_last_month;
	}
	public function get_category_name($role){
		$category_qry  	= 'select prime_category_id,category_name from cw_category where trans_status = 1 and prime_category_id in('.$role.')';
		$category_info  = $this->db->query("CALL sp_a_run ('SELECT','$category_qry')");
		$category_rslt  = $category_info->result_array();
		$category_info->next_result();
		$category_rslt 	= array_reduce($category_rslt, function ($result, $arr) {		
		    $result[$arr['prime_category_id']] = $arr['category_name'];
		    return $result;
		}, array());
		return $category_rslt;
	}
	public function where_month_value($module_name,$pdf_template,$process_month){
		$month_column_query  = 'select cw_print_block.month_column,cw_print_block.print_block_table from cw_print_info inner join cw_print_block on cw_print_block.print_block_for = cw_print_info.prime_print_info_id where print_info_module_id = "'.$module_name.'" and cw_print_info.trans_status = 1 and prime_print_info_id = "'.$pdf_template.'" and print_block_type = 1';
		$month_column_info   = $this->db->query("CALL sp_a_run ('SELECT','$month_column_query')");
		$month_column_rslt 	 = $month_column_info->result();
		$month_column_info->next_result();
		$where_month 		 = $month_column_rslt[0]->month_column;
		$where_table 		 = $month_column_rslt[0]->print_block_table;
		$module_name 		 = implode('","',explode(',', $where_table) ?? []);
		$module_name 		 = str_replace('cw_', '', $module_name);
		$form_setting_qry  	 = 'select field_type,label_name,date_type from cw_form_setting where prime_module_id in ("'.$module_name.'") and cw_form_setting.trans_status = 1';
		$form_setting_info   = $this->db->query("CALL sp_a_run ('SELECT','$form_setting_qry')");
		$form_setting_rslt 	 = $form_setting_info->result_array();
		$form_setting_info->next_result();
		$form_setting_rslt   = array_reduce($form_setting_rslt, function($result, $arr){			
	    	$result[$arr['label_name']] = $arr;
	    	return $result;
		}, array());
		$where_month  = explode(',', $where_month);
		$where_column = "";
		foreach ($where_month as $key => $where_col) {
			$get_label_arr 	= explode('.', $where_col);
			$table_name 	= $get_label_arr[0];
			$label_name 	= $get_label_arr[1];
			$field_type 	= $form_setting_rslt[$label_name]['field_type'];
			$date_type    	= $form_setting_rslt[$label_name]['date_type'];
			if(($label_name ==="transactions_month" && $table_name ==="cw_transactions") || ($label_name ==="apply_on" && $table_name ==="cw_increment")){
				$field_type = 1;
			}
			if((int)$field_type === 4 && (int)$date_type === 1){
				$where_column .= "and DATE_FORMAT(STR_TO_DATE($table_name.$label_name,\"%Y-%m-%d\"),\"%m-%Y\") = \"$process_month\" ";
			}else{
				if($label_name && $process_month){ // [MS 27-11-2024]
					$where_column .= " and $table_name.$label_name =\"$process_month\" ";
				}
			}
		}
		return $where_column;
	}
	//BSK Get All Employees from excel sheet
	public function get_excel_employee_codes($sheet,$excel_row_start,$total_rows,$excel_format_result,$module_id){
		$employee_query  = 'select employee_code,termination_status,resignation_date from cw_employees where trans_status = 1';
		$employee_info   = $this->db->query("CALL sp_a_run ('SELECT','$employee_query')");
		$employee_rslt 	 = $employee_info->result_array();
		$employee_info->next_result();
		// $employee_rslt 	 = array_reduce($employee_rslt, function($result, $arr){			
	    // 	$result[$arr['employee_code']] = $arr;
	    // 	return $result;
		// }, array());
		$employee_rslt_arr = array();
		foreach($employee_rslt as $emp_key => $emp_val){
			$emp_code      = $emp_val['employee_code'];
			$employee_rslt_arr[$emp_code]    = $emp_val;
		}
		$employee_codes_arr = array();
		for ($row = $excel_row_start; $row <= $total_rows; $row++){
			foreach($excel_format_result as $excel_info){
				$field_isdefault        = (int)$excel_info->field_isdefault;
				$mandatory_field        = (int)$excel_info->mandatory_field;
				$field_type             = (int)$excel_info->field_type;
				$pick_table             = $excel_info->pick_table;
				$pick_list_type         = (int)$excel_info->pick_list_type;
				$pick_list_import       = (int)$excel_info->pick_list_import;
				$pick_list              = $excel_info->pick_list;
				$excel_line_column_name = $excel_info->excel_line_column_name;
				$excel_line_value       = $excel_info->excel_line_value;
				if($excel_line_column_name === 'employee_code'){
					$get_cell_value         = ucwords(trim($sheet->getCell("$excel_line_value$row")->getValue()));
					$employee_codes_arr[] = $get_cell_value;
				}
				//resign employee array build
				$employee_status 	= $employee_rslt_arr[$get_cell_value]['termination_status'];
				$resignation_date 	= $employee_rslt_arr[$get_cell_value]['resignation_date'];
				if((int)$employee_status === 1){
					if($excel_line_column_name === 'from_date'){
						$from_date = trim(date('Y-m-d',Date::PHPToExcel($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
						$terminate_emp_arr[$row][$excel_line_column_name] 	= $from_date;
						$terminate_emp_arr[$row]['resignation_date'] 		= $resignation_date;
					}else
					if($excel_line_column_name === 'to_date'){
						$to_date = trim(date('Y-m-d',Date::PHPToExcel($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
						$terminate_emp_arr[$row][$excel_line_column_name] 	= $to_date;
						$terminate_emp_arr[$row]['resignation_date'] 		= $resignation_date;
					}
				}
			}
		}
		// resign employee error 
		foreach ($terminate_emp_arr as $row_key => $row_val) {
			$from_date 		= $row_val['from_date'];
			$to_date 		= $row_val['to_date'];
			$resign_date 	= $row_val['resignation_date'];
			if((strtotime($from_date) > strtotime($resign_date)) || (strtotime($to_date) > strtotime($resign_date))){
				$msg_line = "Employee Already Resigned...";
				$err_column_tabview['error']["$row_key"]  = $msg_line;
			}
		}
		$get_excel_employee_arr = array('employee_codes_arr'=>$employee_codes_arr,'err_column_tabview'=>$err_column_tabview);
		return $get_excel_employee_arr;
	}
	
	public function checkisprocessed($process_month,$where_query,$table_name){
		$exist_qry   = 'select count(*) as exist_count from '.$table_name.' where '.$table_name.'.trans_status =1 '.$where_query.' and process_month = "'.$process_month.'"';
        $exist_info  = $this->db->query("CALL sp_a_run ('SELECT','$exist_qry')");
        $exist_rslt  = $exist_info->result();
        $exist_info->next_result();
        $exist_count = $exist_rslt[0]->exist_count;
        return $exist_count;
	}
	public function excel_exist_check_arr($sheet,$excel_row_start,$total_rows,$excel_format_result){
		$employee_codes_arr = array();	
		foreach($excel_format_result as $excel_info){
			$field_isdefault        = (int)$excel_info->field_isdefault;
			$mandatory_field        = (int)$excel_info->mandatory_field;
			$field_type             = (int)$excel_info->field_type;
			$pick_table             = $excel_info->pick_table;
			$pick_list_type         = (int)$excel_info->pick_list_type;
			$pick_list_import       = (int)$excel_info->pick_list_import;
			$pick_list              = $excel_info->pick_list;
			$excel_line_column_name = $excel_info->excel_line_column_name;
			$excel_line_value       = $excel_info->excel_line_value;
			$myDataArray[$excel_line_column_name] = $sheet->rangeToArray("$excel_line_value$excel_row_start:$excel_line_value$total_rows", NULL, True, True);

			$row_wise_arr 	= array();
			foreach ($myDataArray as $col_key => $value) {
				$i = $excel_row_start;
				foreach ($value as $row_key => $val) {
					$excel_data 	= $val[0];
					$row_wise_arr[$i][$col_key] 	= $excel_data;
					$i++;
				}
			}
		}	

		$date_build_arr = array();
		foreach($row_wise_arr as $r_key => $row_value){
			$f_date     = str_replace('/', '-', $row_value['from_date']);
			$t_date     = str_replace('/', '-', $row_value['to_date']);
			$from_date 	= date('Y-m-d',strtotime($f_date));
			$to_date 	= date('Y-m-d',strtotime($t_date));
			$emp_code 	= $row_value['employee_code'];
			$get_date 	= $this->getDatesFromRange($from_date, $to_date);
			$date_build_arr[$emp_code][$r_key]	= $get_date;
		}

		$err_column_tabview  = array();
		foreach($date_build_arr as $emp_code => $row_value){
			$date_arr  = array();
			foreach ($row_value as $row_key => $date_value) {
				foreach ($date_value as $date_key => $value) {
					if(in_array($value, $date_arr)){
						$msg_line = "Duplicate Date Exists. Please check your excel sheet";
						$err_column_tabview['error']["$row_key"]  = $msg_line;
					}else{
						$date_arr[]	= $value;
					}
				}
			}
		}
		return $err_column_tabview;
	}
	public function getDatesFromRange($start,$end,$format = 'Y-m-d') {
	    $array 			= array();
	    $array_error 	= array();
	    $interval 		= new DateInterval('P1D');
	    $realEnd 		= new DateTime($end);
	    $realEnd->add($interval);
	    $period 		= new DatePeriod(new DateTime($start), $interval, $realEnd);
	    foreach($period as $date) { 
	    	$check_date 	= $date->format($format);
	    	$date_build_arr = $date_build_arr[$r_key];
	    	if(in_array($check_date, $array)){
	    		$array_error[] = $date->format($format);
	    	}else{
	    		$array[] = $date->format($format);
	    	}
	    }
	    return $array;
	}
	
//--------------- DR CODE 5JUL22 FOR TIME OFFICE MIN DATE AND MAX DATE FUNCTION START---------------------------	
	//qry function for select a last payroll process month to compare for all category 
	public function last_pay_process_mon_info($starting_date,$ending_date){
		$last_pay_trans_qry  = 'SELECT date_format(MAX(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y")) , "%m-%Y") AS process_month from cw_transactions where cw_transactions.trans_status = 1 AND fandf != 1';
		// and date_format(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y") , "%Y-%m-%d") >= "'.$starting_date.'"		
		$last_pay_trans_info = $this->db->query("CALL sp_a_run ('SELECT','$last_pay_trans_qry')");
		$last_pay_trans_rslt = $last_pay_trans_info->result();
		$last_pay_trans_info->next_result();
		$process_month       = $last_pay_trans_rslt[0]->process_month;
		if(!$process_month){
			//THERE IS NO ANY PAYROLL PROCESS MONTH THEN GET FINANCIAL START MONTH
			// $process_month_obj   = (object)array('process_month' => date('m-Y'));
			//THERE IS NO ANY PAYROLL PROCESS MONTH THEN GET FINANCIAL START MONTH
			//Sathish changed for last month
			$process_month_obj   = (object)array('process_month' => date('m-Y', strtotime('-1 month', strtotime($starting_date))));
			$process_month_arr   = array(0 => $process_month_obj);
			return $process_month_arr;
		}else{
			return $last_pay_trans_rslt;
		}
	}
	
	//qry function for select a last payroll process month based on employee wise
	public function pay_process_mon_info($employee_code,$starting_date,$ending_date){
		$where_emp_qry     = ''; 
		if($employee_code){
			$where_emp_qry = ' and cw_transactions.employee_code ="'.$employee_code.'"';
		}
		$pay_posting_qry   = 'SELECT role as category,date_format(MAX(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y")) , "%m-%Y") AS process_month from cw_transactions where cw_transactions.trans_status = 1'.$where_emp_qry;
		// and date_format(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y") , "%Y-%m-%d") >= "'.$starting_date.'"		
		$pay_posting_info  = $this->db->query("CALL sp_a_run ('SELECT','$pay_posting_qry')");
		$pay_posting_rslt  = $pay_posting_info->result();
		$pay_posting_info->next_result();

		$process_month     = $pay_posting_rslt[0]->process_month;
		if(!$process_month){
			//IF THIS EMPLOYEE WAS NEW JOINEE TO GET LAST PAYROLL MONTH
			return $this->last_pay_process_mon_info($starting_date,$ending_date);
		}else{
			return $pay_posting_rslt;
		}
	}
	
	//TIME OFFICE SETTING BASED MONTH DAY QRY FUNCTION 
	public function tos_day_qry_fun($entry_parameter){
		$tos_mon_day_qry   = 'select day_conditions,day_count,day_start,day_end FROM cw_tos_month_day INNER JOIN cw_tos_parameter ON cw_tos_parameter.prime_tos_parameter_id = cw_tos_month_day.entry_parameter where cw_tos_parameter.trans_status = 1 and cw_tos_month_day.trans_status = 1 and cw_tos_parameter.prime_tos_parameter_id = "'.$entry_parameter.'"';
		$tos_mon_day_info  = $this->db->query("CALL sp_a_run ('SELECT','$tos_mon_day_qry')");
		$tos_mon_day_rslt  = $tos_mon_day_info->result();
		$tos_mon_day_info->next_result();
		return $tos_mon_day_rslt;
	}

	//TIME ENTRY POSTING MODULE MONTH DAY FUNCTION
	public function tos_posting_mon_day(){
		//Encryption
		$encString      = file_get_contents('php://input');
		$_POST          = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
		$entry_parameter     = $this->input->post('entry_parameter');
		$today_date          = date("Y-m-d");
		$today               = date("d");
		$financial_info      = $this->get_leave_financial_details();
		$prime_financial_id  = $financial_info[0]->prime_leave_financial_year_id;	
		$starting_date       = date('Y-m-d',strtotime($financial_info[0]->starting_date));	
		$ending_date         = date('Y-m-d',strtotime($financial_info[0]->ending_date));
		//TO CALL A TIME OFFICE SETTING BASED MONTH DAY QRY FUNCTION 
		$tos_mon_day_rslt    = $this->tos_day_qry_fun($entry_parameter);
		if($tos_mon_day_rslt[0]){
			$day_conditions      = (int)$tos_mon_day_rslt[0]->day_conditions;
			$day_count           = $tos_mon_day_rslt[0]->day_count;
			$day_start           = $tos_mon_day_rslt[0]->day_start;
			$day_end             = $tos_mon_day_rslt[0]->day_end;

			$pay_posting_result  = $this->last_pay_process_mon_info($starting_date,$ending_date);
			$process_month       =  $pay_posting_result[0]->process_month;
			
			$month_day_arr       = $this->min_max_date_fun($prime_financial_id,$starting_date,$ending_date,$day_conditions,$day_count,$tos_mon_day_rslt,$process_month);
			$min_date            = $month_day_arr['salary_start_date'];
			$max_date            = $month_day_arr['salary_end_date'];
			$year_end_date       = $month_day_arr['year_end_date'];

			echo json_encode(array('success' => true, 'message' => 'Success.!', 'min_date' => $min_date, 'max_date' => $max_date, 'year_end_date' => $year_end_date,"starting_date" => date('d-m-Y',strtotime($starting_date)),"ending_date" => date('d-m-Y',strtotime($ending_date))));
		}else{
			echo json_encode(array('success' => false, 'message' => 'Please add Time Office Month Day Settings for Process to Time Entry.! Please Contact Admin.!',"starting_date" => $starting_date,"ending_date" => $ending_date));
		}
	}

	//PAYROLL PROCESS WISE SALARY START DATE AND END DATE GET
	public function tos_day_info($employee_code,$entry_parameter){
		//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));	
		$ending_date            = date('Y-m-d',strtotime($financial_info[0]->ending_date));
		
		//TO CALL A TIME OFFICE SETTING BASED MONTH DAY QRY FUNCTION 
		$month_day_result       = $this->tos_day_qry_fun($entry_parameter);
		if($month_day_result){
			$day_conditions      = (int)$month_day_result[0]->day_conditions;
			$day_count           = $month_day_result[0]->day_count;
			$day_start           = "";
			$day_end             = "";
			$process_month       = "";
			$next_month          = "";

			$pay_posting_result  = $this->pay_process_mon_info($employee_code,$starting_date,$ending_date);
			$process_month       =  $pay_posting_result[0]->process_month;
			$month_day_arr       = $this->min_max_date_fun($prime_financial_id,$starting_date,$ending_date,$day_conditions,$day_count,$month_day_result,$process_month);
			return $month_day_arr;
		}else{
			return false;
		}
	}
	//PAYROLL PROCESS WISE SALARY START DATE AND END DATE GET
	public function leave_month_day($permission_date,$employee_code,$entry_parameter){
		//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));	
		$ending_date            = date('Y-m-d',strtotime($financial_info[0]->ending_date));
		//TO CALL A TIME OFFICE SETTING BASED MONTH DAY QRY FUNCTION 
		$month_day_result       = $this->tos_day_qry_fun($entry_parameter);
		if($month_day_result){
			$day_conditions      = (int)$month_day_result[0]->day_conditions;
			$day_count           = $month_day_result[0]->day_count;
			if((int)$day_conditions === 3){
				//GET LAST DATE FOR CUTTOFF TYPE ONLY
				$day_start      = $month_day_result[0]->day_start;
				$day_end        = $month_day_result[0]->day_end;					
			}
			$permission_dates  	  = explode('-', $permission_date);
			$permission_date_val  = $permission_dates[2];
			$process_month        =  date('m-Y',strtotime($permission_date));
			if($permission_date_val < $day_start){
				$process_month        = date('m-Y',strtotime("-1 month",strtotime("01-".$process_month)));
			}
			//$month_day_arr       = $this->min_max_date_fun($prime_financial_id,$starting_date,$ending_date,$day_conditions,$day_count,$month_day_result,$process_month);

			$month_day_arr       = $this->tos_sal_strt_end_info($entry_parameter,$process_month);
			$month_day_arr['year_end_date'] = $ending_date;
			return $month_day_arr;
		}else{
			return false;
		}
	}
	// //MIN AND MAX DATE GET FUNCTION
	public function min_max_date_fun($prime_financial_id,$starting_date,$ending_date,$day_conditions,$day_count,$month_day_result,$process_month){
		if(!$process_month){			
			$process_month = date("m-Y",strtotime($starting_date));
			$day_start     = date('d',strtotime($starting_date));
			$day_end       = date('d',strtotime($ending_date));
		}else{
			if((int)$day_conditions === 3){
				//GET LAST DATE FOR CUTTOFF TYPE ONLY
				$day_start     = $month_day_result[0]->day_start;
				$day_end       = $month_day_result[0]->day_end;		
				$next_month    = date('m-Y',strtotime("+1 month",strtotime("01-".$process_month)));			
			}else{
				$day_start     = '01';		
				// WILL PLUSED ONE FOR REASON TIME ENTRY WAS CHECK AFTER TRANSACTION MONTH NOT PAYROLL PROCESSED MONTH SAME AS LIKE API MOBILE ARN 28-02-2026 (FOR LIKE REQUEST MODULES)
				$next_month    = date('m-Y',strtotime("+1 month",strtotime("01-".$process_month)));			
				// $next_month    = date('m-Y',strtotime("01-".$process_month));
				$day_end       = date('t',strtotime("01-".$next_month));
				//BSK changed this due to first month process issue
				/*$next_month    = date('m-Y',strtotime("+1 month",strtotime("01-".$process_month)));
				$day_end       = date('t',strtotime("01-".$next_month));*/
			}
		}
		
		$today_date        = date('d-m-Y');
		$salary_end_year   = "12-".date('Y');
		if($day_conditions === "" || $day_start === "" || $day_end === ""){
			return false;
		}else{
			if((int)$day_conditions === 3){
				$sal_start         = $day_start;
				//For Current month between days increment
				$date              = new DateTime("01-$next_month 00:00:00");
				$date->modify('-1 month');
				$salary_start_date = $date->format("$sal_start-m-Y");	
				$salary_end_date   = date('d-m-Y',strtotime("$day_end-".$next_month));
				$year_end_date     = date("d-m-Y",strtotime($ending_date));
			}else{
				$sal_start         = $day_start;
				$date              = new DateTime("01-$next_month 00:00:00");
				$salary_start_date = $date->format("$sal_start-m-Y");	
				$salary_end_date   = date("d-m-Y",strtotime($day_end."-".$next_month));
				$year_end_date     = date("d-m-Y",strtotime($ending_date));
			}
			$month_day_arr      = array("salary_start_date" => $salary_start_date,"salary_end_date" => $salary_end_date,"year_end_date" => $year_end_date,"starting_date" => $starting_date,"ending_date" => $ending_date);

			return $month_day_arr;
		}
	}

	//PROCESS MONTH WISE SALARY START DATE AND END DATE GET
	public function tos_sal_strt_end_info($process_parameter,$process_month){
		$month_day_result      = $this->tos_day_qry_fun((int)$process_parameter);
		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;
			// $prev_month        = date('m-Y',strtotime("-1 month",strtotime($in_date)));
			if((int)$day_conditions === 3){
				$sal_start         = $day_start;
				//For Current month between days increment
				if($process_month){
					$date              = new DateTime("01-$process_month 00:00:00");
					$date->modify('-1 month');
					$salary_start_date = $date->format("$sal_start-m-Y");	
					$salary_end_date   = date('d-m-Y',strtotime("$day_end-".$process_month));
				}
			}else{
				$sal_start         = '01';
				if((int)$day_conditions === 2){
					$day_end           = date('t',strtotime("01-".$process_month));
				}
				$date              = new DateTime("01-$process_month 00:00:00");
				$salary_start_date = $date->format("$sal_start-m-Y");	
				$salary_end_date   = date("d-m-Y",strtotime($day_end."-".$process_month));
			}
			$sal_start_end_arr     = array("salary_start_date" => $salary_start_date,"salary_end_date" => $salary_end_date);
			return $sal_start_end_arr;
		}
	}
	//--------------- DR CODE 5JUL22 FOR TIME OFFICE MIN DATE AND MAX DATE FUNCTION END---------------------------
	//DR FUNCTION FOR GET A SHIFT IN AND OUT TIME FOR VALIDATE A PERMISSION TIME
	public function shift_time_qry($shift_name){
		//CHECK FROM SHIFT MASTER FOR FROM TIME AND TO TIME VALIDATION QUERY
		$shift_master_qry     = 'SELECT * FROM cw_shift_master WHERE cw_shift_master.prime_shift_master_id = "'.$shift_name.'" and cw_shift_master.trans_status = 1';
		$shift_master_info    = $this->db->query("CALL sp_a_run ('SELECT','$shift_master_qry')");
		$shift_master_rslt    = $shift_master_info->result();
		$shift_master_info->next_result();
		return $shift_master_rslt;
	}
		//Monthly input mapping and Muster role wizard
	public function get_time_office_components(){
		$count_type_arr   =  array(""=>"---- Select Column----","P"=>"Present Count","A"=>"Absent Count","I"=>"Invalid Count","L"=>"Total Leaves","H"=>"Holiday Count","W"=>"Weekoff Count","OD"=>"Onduty Count","M"=>"Manualpunch Count","excess_ot"=>"Excess Hours OT","shift_ot"=>"Shift OT","special_ot"=>"Special OT","total_ot"=>"Total Hours OT","prev_total_ot"=>"Previous Month OT","prev_total_ot_mins"=>"Previous Month OT Mins","paid_leave"=>"Paid Leaves","paid_days"=>"Paid Days","weekoff_working"=>"WEEKOFF WORKING DAYS","weekoff_work_hours"=>"WEEKOFF WORKING HOURS","weekoff_work_mins"=>"WEEKOFF WORKING MINUTES","holiday_working"=>"HOLIDAY WORKING DAYS","holiday_work_hours"=>"HOLIDAY WORKING HOURS","holiday_work_mins"=>"HOLIDAY WORKING MINUTES","late_days"=>"LATE DAYS","late_hours"=>"LATE HOURS","late_mins"=>"LATE MINUTES","perm_days"=>"PERMISSION DAYS","perm_hours"=>"PERMISSION HOURS","perm_mins"=>"PERMISSION MINUTES","total_encash"=>"TOTAL ENCASH DAYS","lop_days"=>"Total Lop Days","food_count"=>"Food Allowance Count","1st_count"=>"1st Shift Count","2nd_count"=>"2nd Shift Count","n_count"=>"Night Shift Count");

		//LEAVE CREATION QRY FOR GET A ALL USED LEAVE NAME for add a 
		$leave_name_qry    = 'SELECT prime_leave_creation_id,LOWER(leave_name) as leave_name,CONCAT_WS(" ",leave_name,"count") as leave_count FROM cw_leave_creation WHERE trans_status = 1' ;
		$leave_name_info   = $this->db->query("CALL sp_a_run ('SELECT','$leave_name_qry')");
		$leave_name_rslt   = $leave_name_info->result_array();
		$leave_name_info->next_result();
		$leave_name_arr    = array_reduce($leave_name_rslt, function ($result, $arr) {		
		    $result[$arr['leave_name']]          = $arr['leave_count'];
		    return $result;
		}, array());
		$leave_opening_qry    = 'SELECT prime_leave_creation_id,leave_name,CONCAT("opening_", LOWER(leave_name) ) as leave_opening_name,CONCAT_WS(" Opening ",LOWER(leave_name)," count") as opening_count,CONCAT("encash_",LOWER(leave_name)) as leave_encash_name,CONCAT_WS(" Encash ",LOWER(leave_name)," count") as encash_count,CONCAT("balance_",LOWER(leave_name)) as balance_leave_name,CONCAT_WS(" Balance ",LOWER(leave_name), "count") as balance_count FROM cw_leave_creation WHERE trans_status = 1 and leave_opening = 1';
		$leave_opening_info   = $this->db->query("CALL sp_a_run ('SELECT','$leave_opening_qry')");
		$leave_opening_rslt   = $leave_opening_info->result_array();
		$leave_opening_info->next_result();

		$leave_opening_arr    = array_reduce($leave_opening_rslt, function ($result, $arr) {
		    $result[$arr['leave_encash_name']]   = $arr['encash_count'];
		    $result[$arr['balance_leave_name']]  = $arr['balance_count'];
		    $result[$arr['leave_opening_name']]  = $arr['opening_count'];
		    return $result;
		}, array());

		//sHIFT MASTER QRY FOR GET A ALL SHIFT NAME
		$shift_name_qry    = 'SELECT prime_shift_master_id,shift_name,CONCAT_WS(" ",shift_name,"count") as shift_count FROM cw_shift_master WHERE trans_status = 1';
		$shift_name_info   = $this->db->query("CALL sp_a_run ('SELECT','$shift_name_qry')");
		$shift_name_rslt   = $shift_name_info->result_array();
		$shift_name_info->next_result();

		$shift_name_arr    = array_reduce($shift_name_rslt, function ($result, $arr) {		
		    $result[$arr['shift_name']] = $arr['shift_count'];
		    return $result;
		}, array());

		$final_arr = $count_type_arr + $leave_name_arr + $shift_name_arr + $leave_opening_arr;
		return $final_arr;
	}
	//Muster Report and posting query
	public function get_muster_details($emp_rslt_arr,$start_date,$end_date,$category,$emp_component,$show_time_office_comp_arr,$from,$process_month,$process_type){
		$where_query     = "";
		$trans_query     = "";
		$supp_query      = "";
		if($process_type === 1){
			$where_query = ' and cw_monthly_input.employee_code = "'.$process_emp_code.'" ';
			$trans_query = ' and cw_transactions.employee_code = "'.$process_emp_code.'" ';
			$supp_query  = ' and emp_code = "'.$process_emp_code.'" ';
		}else
		if($process_type === 2){
			$where_query = ' and cw_monthly_input.role = "'.$category.'"';
			$trans_query = ' and cw_transactions.role = "'.$category.'"';
			$supp_query  = ' and category = "'.$category.'"';
		}   
			
		$table_content            = "";
		$tr_head                  = "";
		$tr_line                  = "";
		$holiday_rslt             = "";
		$weekoff_rslt             = "";
		$leave_financial_info     = $this->get_leave_financial_details();
		$financial_year_id        = $leave_financial_info[0]->prime_leave_financial_year_id;

		//time office components count array build codes 
		$count_type_arr   =  array(""=>"---- Select Column----","P"=>"Present Count","A"=>"Absent Count","I"=>"Invalid Count","L"=>"Total Leaves","H"=>"Holiday Count","W"=>"Weekoff Count","OD"=>"Onduty Count","M"=>"Manualpunch Count","excess_ot"=>"Excess Hours OT","shift_ot"=>"Shift OT","special_ot"=>"Special OT","total_ot"=>"Total Hours OT","prev_total_ot"=>"Previous Month OT","prev_total_ot_mins"=>"Previous Month OT Mins","paid_leave"=>"Paid Leaves","paid_days"=>"Paid Days","weekoff_working"=>"WEEKOFF WORKING DAYS","weekoff_work_hours"=>"WEEKOFF WORKING HOURS","weekoff_work_mins"=>"WEEKOFF WORKING MINUTES","holiday_working"=>"HOLIDAY WORKING DAYS","holiday_work_hours"=>"HOLIDAY WORKING HOURS","holiday_work_mins"=>"HOLIDAY WORKING MINUTES","late_days"=>"LATE DAYS","late_hours"=>"LATE HOURS","late_mins"=>"LATE MINUTES","perm_days"=>"PERMISSION DAYS","perm_hours"=>"PERMISSION HOURS","perm_mins"=>"PERMISSION MINUTES","total_encash"=>"TOTAL ENCASH DAYS","lop_days"=>"Total Lop Days","food_count"=>"Food Allowance Count","1st_count"=>"1st Shift Count","2nd_count"=>"2nd Shift Count","n_count"=>"Night Shift Count");

		//LEAVE CREATION QRY FOR GET A ALL LEAVE NAME for add a 
		$leave_name_qry    = 'SELECT prime_leave_creation_id,LOWER(leave_name) as leave_name,CONCAT_WS(" ",leave_name,"count") as leave_count FROM cw_leave_creation WHERE trans_status = 1';
		$leave_name_info   = $this->db->query("CALL sp_a_run ('SELECT','$leave_name_qry')");
		$leave_name_rslt   = $leave_name_info->result_array();
		$leave_name_info->next_result();

		$leave_name_arr    = array_reduce($leave_name_rslt, function ($result, $arr) {		
		    $result[$arr['leave_name']]          = $arr['leave_count'];
		    return $result;
		}, array());
		//print_r($leave_name_arr); die;
 		$leave_opening_qry    = 'SELECT prime_leave_creation_id,leave_name,CONCAT("opening_", LOWER(leave_name) ) as leave_opening_name,CONCAT_WS(" Opening ",LOWER(leave_name)," count") as opening_count,CONCAT("encash_",LOWER(leave_name)) as leave_encash_name,CONCAT_WS(" Encash ",LOWER(leave_name)," count") as encash_count,CONCAT("balance_",LOWER(leave_name)) as balance_leave_name,CONCAT_WS(" Balance ",LOWER(leave_name), "count") as balance_count FROM cw_leave_creation WHERE trans_status = 1 and leave_opening = 1';
		$leave_opening_info   = $this->db->query("CALL sp_a_run ('SELECT','$leave_opening_qry')");
		$leave_opening_rslt   = $leave_opening_info->result_array();
		$leave_opening_info->next_result();

		$leave_opening_arr    = array_reduce($leave_opening_rslt, function ($result, $arr) {
		    $result[$arr['leave_encash_name']]   = $arr['encash_count'];
		    $result[$arr['balance_leave_name']]  = $arr['balance_count'];
		    $result[$arr['leave_opening_name']]  = $arr['opening_count'];
		    return $result;
		}, array());
		
		//SHIFT MASTER QRY FOR GET A ALL SHIFT NAME
		$shift_name_qry    = 'SELECT prime_shift_master_id,shift_name,CONCAT_WS(" ",shift_name,"count") as shift_count FROM cw_shift_master WHERE trans_status = 1';
		$shift_name_info   = $this->db->query("CALL sp_a_run ('SELECT','$shift_name_qry')");
		$shift_name_rslt   = $shift_name_info->result_array();
		$shift_name_info->next_result();

		$shift_name_arr    = array_reduce($shift_name_rslt, function ($result, $arr) {		
		    $result[$arr['shift_name']] = $arr['shift_count'];
		    return $result;
		}, array());
		
		$all_time_office_comp_arr = $count_type_arr + $leave_name_arr + $shift_name_arr + $leave_opening_arr;

		//day status legends name get qry
		$day_status_qry 	     = 'SELECT prime_day_status_legends_id,legends,custom_value,day_description FROM cw_day_status_legends where cw_day_status_legends.trans_status = 1';
		$day_status_info         = $this->db->query("CALL sp_a_run ('SELECT','$day_status_qry')");
		$day_status_rslt 	     = $day_status_info->result_array();
		$day_status_info->next_result();

		$day_status_rslt         = array_reduce($day_status_rslt, function ($result, $arr) {		
		    $result[$arr['legends']] = $arr['custom_value'];
		    return $result;
		}, array());

		$add_qry     = '';
		if($this->config->item("db_name") === 'rebar_hrms_db' || $this->config->item('MANUF') == 1){
			$add_qry           = ',f_shift,s_shift,n_shift';
			$prev_month_dt     = date("Y-m-d",strtotime("01-".$process_month));
			$prev_month        = date('m-Y',strtotime("$prev_month_dt -1 month"));
			$tos_salary_dates          = $this->tos_sal_strt_end_info("4",$prev_month); // 4 => Posting Entry
			$pre_start_date            = date("Y-m-d",strtotime($tos_salary_dates['salary_start_date']));
			$pre_end_date              = date("Y-m-d",strtotime($tos_salary_dates['salary_end_date']));

			if($this->config->item("db_name") === 'rebar_hrms_db'){
				$add_qry = ',food_a,f_shift,s_shift';
				$prev_time_qry 	   = 'SELECT employee_code,SUM(approved_ot_mins) as approved_ot_mins FROM cw_time_entry inner join cw_shift_master on cw_shift_master.prime_shift_master_id = cw_time_entry.shift_id where cw_time_entry.trans_status = 1 and att_date between "'.$pre_start_date.'" and "'.$pre_end_date.'" and approved_ot_mins > 0 group by employee_code';
				$prev_time_info    = $this->db->query("CALL sp_a_run ('SELECT','$prev_time_qry')");
				$prev_time_arr 	   = $prev_time_info->result_array();
				$prev_time_info->next_result();
				$prev_time_rslt = array();
				foreach ($prev_time_arr as $key => $value){
					$prev_time_rslt[$value['employee_code']] = $value;
				}
			}	
		}

		//QUERY FOR GET A TIME ENTRY TABLE
		$time_qry 	   = 'SELECT permission_type,employee_code,att_date,cw_shift_master.shift_name,punch_in,punch_out,total_work_hours,total_late_hours,total_excess_hours,first_half_status,second_half_status,whole_day_status,total_permission,approved_ot_mins,approved_shift_ot,approved_special_ot,late_in,total_permission '.$add_qry.' FROM cw_time_entry inner join cw_shift_master on cw_shift_master.prime_shift_master_id = cw_time_entry.shift_id where cw_time_entry.trans_status = 1 and att_date between "'.$start_date.'" and "'.$end_date.'"';
		$time_info     = $this->db->query("CALL sp_a_run ('SELECT','$time_qry')");
		$time_arr 	   = $time_info->result_array();
		$time_info->next_result();

		$time_rslt = array();
		foreach ($time_arr as $key => $value){
			$time_rslt[$value['employee_code']][$value['att_date']] = $value;
		}

		//Get invalid punch
		$time_wrong_qry 	= 'SELECT employee_code,att_date,punch_in,punch_out,record_type FROM cw_time_wrong_entry where cw_time_wrong_entry.trans_status = 1 and att_date between "'.$start_date.'" and "'.$end_date.'"';
		$time_wrong_info   = $this->db->query("CALL sp_a_run ('SELECT','$time_wrong_qry')");
		$time_wrong_rslt 	= $time_wrong_info->result_array();
		$time_wrong_info->next_result();

		$time_wrong_rslt = array_reduce($time_wrong_rslt, function ($result, $arr) {
		    $result[$arr['employee_code']][$arr['att_date']] = $arr;
		    return $result;
		}, array());

		//query for get a all employees picklist componenets details array
		$get_components        = 'select GROUP_CONCAT(label_name) as label_name from `cw_form_setting` where prime_module_id = "employees" and input_view_type in (1,2) and field_type = 5 ORDER BY label_name';
		$get_components_info   = $this->db->query("CALL sp_a_run ('SELECT','$get_components')");
		$get_components_result = $get_components_info->result();
		$get_components_info->next_result();
		$label_names           = $get_components_result[0]->label_name;
	
		$emp_pick_query        = 'SELECT role as category,'.$label_names.',employee_code from cw_employees WHERE   trans_status = 1';
		$emp_pick_info         = $this->db->query("CALL sp_a_run ('SELECT','$emp_pick_query')");
		$emp_pick_rlst         = $emp_pick_info->result_array();
		$emp_pick_info->next_result();

		$emp_picklist_arr      = array_reduce($emp_pick_rlst, function($result, $arr){	
	    	$result[$arr['employee_code']] = $arr;
	    	return $result;
		}, array());

		//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'];	

		if($holiday_entry === 2){
			//QUERY FOR GET A EMPLOYEE PICKLIST COMPOENENT DETAILS 
			$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_label_name      = $holid_component_result[0]->label_name;

			//QUERY FOR GET A HOLIDAY ENTRY TABLE
			$holiday_qry   = 'SELECT holiday_date,component_value 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 cw_holiday_entry_holiday_data.trans_status = 1 and holiday_date between "'.$start_date.'" and "'.$end_date.'"';
			$holiday_info  = $this->db->query("CALL sp_a_run ('SELECT','$holiday_qry')");
			$holiday_rslt  = $holiday_info->result_array();
			$holiday_info->next_result();

			$holiday_rslt  = array_reduce($holiday_rslt, function($result, $arr){		
			    $result[$arr['holiday_date']] = $arr['component_value'];
			    return $result;
			}, array());
		}

		//GET WEEKOFF DAY FROM WEEKOFF IMPORT OR WEEKOFF ENTRY BASED ON GENERAL SETTINGS
			//QUERY FOR GET A WEEKOFF IMPORT TABLE
		$weekoff_qry   = 'SELECT employee_code,weekoff_date,weekoff_type FROM cw_weekoff_import where cw_weekoff_import.trans_status = 1 and weekoff_date between "'.$start_date.'" and "'.$end_date.'"';
		$weekoff_info  = $this->db->query("CALL sp_a_run ('SELECT','$weekoff_qry')");
		$weekoff_rslt  = $weekoff_info->result_array();
		$weekoff_info->next_result();

		$weekoff_rslt  = array_reduce($weekoff_rslt, function($result, $arr){		
		    $result[$arr['employee_code']][$arr['weekoff_date']] = $arr;
		    return $result;
		}, array());
		
		//QUERY FOR GET A SHIFT NAME COUNT FROM TIME ENTRY TABLE
		$shift_master_qry   = 'SELECT employee_code,att_date,cw_shift_master.shift_name,COUNT(*) as shift_count FROM cw_time_entry inner join cw_shift_master on cw_shift_master.prime_shift_master_id = cw_time_entry.shift_id where cw_time_entry.trans_status = 1 and cw_shift_master.trans_status = 1 and cw_time_entry.att_date between "'.$start_date.'" and "'.$end_date.'" GROUP BY employee_code,cw_shift_master.shift_name';
		$shift_master_info  = $this->db->query("CALL sp_a_run ('SELECT','$shift_master_qry')");
		$shift_master_rslt  = $shift_master_info->result_array();
		$shift_master_info->next_result();
		
		$shift_master_rslt  = array_reduce($shift_master_rslt, function ($result, $arr) {		
		    $result[$arr['employee_code']][$arr['shift_name']] = $arr['shift_count'];
		    return $result;
		}, array());

		//QUERY FOR GET A LEAVE NAME COUNT FROM LEAVE ENTRY TABLE
		$leave_name_count_qry   = 'SELECT employee_code,leave_date,LOWER(cw_leave_creation.leave_name) as leave_name,SUM(leave_count) as leave_count,cw_leave_creation.paid_leave FROM cw_leave_entry inner join cw_leave_creation on cw_leave_creation.prime_leave_creation_id = cw_leave_entry.leave_type where cw_leave_entry.trans_status = 1 and cw_leave_creation.trans_status = 1 and cw_leave_entry.leave_date between "'.$start_date.'" and "'.$end_date.'" and cw_leave_entry.leave_status = 2 GROUP BY employee_code,cw_leave_creation.leave_name';
		$leave_name_count_info  = $this->db->query("CALL sp_a_run ('SELECT','$leave_name_count_qry')");
		$leave_name_count_rslt  = $leave_name_count_info->result_array();
		$leave_name_count_info->next_result();
		$leave_count_arr = array();
		$paid_count_arr  = array();
		$lop_count_arr   = array();
		foreach ($leave_name_count_rslt as $key => $value) {
			$employee_code = $value['employee_code'];
			$leave_name    = $value['leave_name'];
			$leave_count   = $value['leave_count'];
			$paid_leave    = $value['paid_leave'];
			$leave_count_arr[$employee_code][$leave_name] = $value;
			if((int)$paid_leave === 1){
				$paid_count_arr[$employee_code] += $leave_count;
			}else{
				$lop_count_arr[$employee_code] += $leave_count;
			}		
		}

		$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  .= " encash_".$leave_name."+";
				//calculate leave balance
                $credit_columns  .= '(('.$leave_name."+".$leave_name.'_credit)-('.$leave_name.'_debit + used_'.$leave_name.'+ pending_'.$leave_name.'+ cw_leave_opening.encash_'.$leave_name.')) as balance_'.$leave_name.',';
                $opening_columns .='('.$leave_name."+".$leave_name.'_credit) as opening_'.$leave_name.',';
            }			
		}
		$select_columns       = rtrim($select_columns,"+");
		$credit_columns       = rtrim($credit_columns,",");
		$opening_columns      = rtrim($opening_columns,",");
		//Encash data result
		$leave_encash_count_qry   = 'SELECT *,SUM('.$select_columns.') as total_encash FROM cw_leave_encash_days where cw_leave_encash_days.trans_status = 1 and cw_leave_encash_days.process_month = "'.$process_month.'" GROUP BY cw_leave_encash_days.employee_code';
		$leave_encash_count_info  = $this->db->query("CALL sp_a_run ('SELECT','$leave_encash_count_qry')");
		$leave_encash_count_rslt  = $leave_encash_count_info->result_array();
		$leave_encash_count_info->next_result();

		$leave_encash_count_rslt  = array_reduce($leave_encash_count_rslt, function ($result, $arr) {		
		    $result[$arr['employee_code']] = $arr;
		    return $result;
		}, array());

		$leave_bal_qry = 'SELECT '.$credit_columns.',employee_code  from cw_leave_opening where trans_status = 1';
		$leave_bal_info = $this->db->query("CALL sp_a_run ('SELECT','$leave_bal_qry')");
		$leave_bal_rslt = $leave_bal_info->result_array();
		$leave_bal_info->next_result();
		$leave_bal_arr  = array_reduce($leave_bal_rslt, function ($result, $arr) {		
		    $result[$arr['employee_code']] = $arr;
		    return $result;
		}, array());
		$opening_leave_qry = 'SELECT '.$opening_columns.',employee_code  from cw_leave_opening where trans_status = 1';
		$opening_leave_info = $this->db->query("CALL sp_a_run ('SELECT','$opening_leave_qry')");
		$opening_leave_rslt = $opening_leave_info->result_array();
		$opening_leave_info->next_result();
		$opening_leave_arr  = array_reduce($opening_leave_rslt, function ($result, $arr) {		
		    $result[$arr['employee_code']] = $arr;
		    return $result;
		}, array());

		//Get Date Period Between Two Dats
		$date_period  = new DatePeriod(
		     new DateTime($start_date),
		     new DateInterval('P1D'),
		     new DateTime(date("Y-m-d",strtotime("+1 days",strtotime($end_date))))
		);
		//custom array create for get different time office count
		$leave_arr      = array("L"=>1,"FL"=>0.5,"SL"=>0.5,"LP"=>0.5,"PL"=>0.5,"LM"=>0.5,"ML"=>0.5,"OL"=>0.5,"LO"=>0.5,"LL"=>1,"WL"=>0.5,"LW"=>0.5,"UL"=>0.5,"LU"=>0.5,"IL"=>0.5,"LI"=>0.5,"IAP"=>0.5,"APL"=>0.5);
		$present_arr    = array("AP"=>1,"P"=>1,"FP"=>0.5,"SP"=>0.5,"LP"=>0.5,"PL"=>0.5,"LAP"=>0.5,"APL"=>0.5,"PM"=>0.5,"MP"=>0.5,"OP"=>0.5,"PO"=>0.5,"OAP"=>0.5,"APO"=>0.5,"PP"=>1,"IP"=>0.5,"PI"=>0.5,"PU"=>0.5,"UP"=>0.5);
		$onduty_arr     = array("O"=>1,"FO"=>0.5,"SO"=>0.5,"OP"=>0.5,"PO"=>0.5,"OAP"=>0.5,"APO"=>0.5,"OM"=>0.5,"MO"=>0.5,"OL"=>0.5,"LO"=>0.5,"OO"=>1,"WO"=>0.5,"OW"=>0.5,"UO"=>0.5,"OU"=>0.5,"IO"=>0.5,"OI"=>0.5);
		$mpunch_arr     = array("M"=>1,"FM"=>0.5,"SM"=>0.5,"MP"=>0.5,"PM"=>0.5,"OM"=>0.5,"MO"=>0.5,"ML"=>0.5,"LM"=>0.5,"MM"=>1,"WM"=>0.5,"MW"=>0.5,"UM"=>0.5,"MU"=>0.5,"IM"=>0.5,"MI"=>0.5);
		$weekoff_arr    = array("W"=>1,"WL"=>0.5,"LW"=>0.5,"WO"=>0.5,"OW"=>0.5,"WM"=>0.5,"MW"=>0.5);
		$unpunch_arr    = array("U"=>1,"UL"=>0.5,"LU"=>0.5,"UO"=>0.5,"OU"=>0.5,"UM"=>0.5,"MU"=>0.5,"UP"=>0.5,"PU"=>0.5,"FP"=>0.5,"SP"=>0.5,"IU"=>0.5,"UI"=>0.5,"FL"=>0.5,"SL"=>0.5,"IAP"=>0.5,"APL"=>0.5);
		$invalid_arr    = array("I"=>1,"IL"=>0.5,"LI"=>0.5,"IO"=>0.5,"OI"=>0.5,"IM"=>0.5,"MI"=>0.5,"IU"=>0.5,"UI"=>0.5,"IP"=>0.5,"PI"=>0.5,"IAP"=>0.5,"APL"=>0.5);
		//for employee component details are show in table
		$emp_comp_arr   = explode('","', $emp_component);		
		$posting_value        = "";		
		foreach($emp_rslt_arr as $emp_code){
			$employee_code        = $emp_code['employee_code'];
			$employees_id         = $emp_code['prime_employees_id'];
			$emp_name             = $emp_code['emp_name'];
			$category             = $emp_code['role'];
			$emp_act_sts          = $emp_code['termination_status'];
			$emp_doj              = date("Y-m-d",strtotime($emp_code['date_of_joining']));
			$emp_resign_date      = date("Y-m-d",strtotime($emp_code['last_working_date']));
			$posting_value       .= '("'.$category.'","'.$employees_id.'","'.$emp_doj.'","'.$employee_code.'","'.$process_month.'","'.$emp_act_sts.'","'.$emp_name.'"';
			$posting_qry          = "role,employees_id,date_of_joining,employee_code,process_month,termination_status,emp_name";
			$comp_head            = "";
			$comp_line            = "";
			$lop_head             = "";
			$lop_line             = "";
			$paid_head            = "";
			$paid_line            = "";	
			$update_qry           = "";	
			$present_count        = 0;
			$absend_count         = 0;
			$invalid_count        = 0;
			$late_count           = 0;
			$leave_count          = 0;
			$shift_count          = 0;
			$leave_name_count     = 0;
			$woff_count           = 0;
			$woff_work_count      = 0;
			$woff_work_hours      = 0;
			$woff_work_mins       = 0;
			$holiday_count        = 0;
			$holiday_work_count   = 0;
			$holiday_work_hours   = 0;
			$holiday_work_mins    = 0;
			$late_count           = 0;
			$late_hours           = 0;
			$late_mins            = 0;
			$permission_count     = 0;
			$permission_hours     = 0;
			$permission_mins      = 0;
			$onduty_count         = 0;
			$mpunch_count         = 0;
			$paid_days_count      = 0;
			$paid_leave_count     = 0;
			$ilop_count           = 0;
			$excess_ot_mins       = 0;
			$shift_ot_mins        = 0;
			$special_ot_mins      = 0;
			$total_ot_mins        = 0; 
			$prev_total_ot_mins   = 0; 
			$food_count           = 0; 
			$first_count          = 0; 
			$second_count         = 0; 
			$present_shift        = array();
			//Employee master component
			foreach ($emp_comp_arr as $key => $value){
				$comp_val    = $emp_code[$value];
				if($value === "role"){
					$value = 'Category';
				}else
				if($value === "termination_status"){
					$value = 'Employee Status';
				}

				$value       = str_replace("_"," ",$value);
				$comp_head  .= "<th>$value</th>";
				$comp_line  .= "<td>$comp_val</td>";
			}
			
			$tr_head    = "<tr><th>Employee Code</th><th>Employee Name</th>$comp_head";
			$tr_line   .= "<tr><td>$employee_code</td><td>$emp_name</td> $comp_line";
			$company_info       = $this->company_info();
			$coff_based_on      = $company_info[0]->coff_based_on; //Get from company info module.
			$coff_check_qry     = "";
			if($coff_based_on  !== 'role' && $coff_based_on !== '0'){
				$check_input    = $emp_code[$coff_based_on];
				if($check_input){
					$coff_check_qry = ' and FIND_IN_SET('.$check_input.',check_input)';
				}				
			}
			//echo $coff_based_on; die;
			//$max_ot_mins = 0;
			//Check Max OT Hours			
			/*$check_inp_qry     = 'SELECT max_ot_hours from cw_coff_settings where FIND_IN_SET('.$category.', cw_coff_settings.category) '.$coff_check_qry;
			$check_inp_info    = $this->db->query("CALL sp_a_run ('SELECT','$check_inp_qry')");
			$check_inp_result  = $check_inp_info->result();
			$check_inp_info->next_result();	
			$max_ot_hours   = $check_inp_result[0]->max_ot_hours;
			$max_ot_mins    = $this->hourstomins($max_ot_hours);*/

			//Date between from and to date			
			foreach ($date_period as $key => $value){
			    $att_day                = $value->format('d');      
			    $att_date               = $value->format('Y-m-d');
			    $dis_date               = $value->format('d-m-Y');
			    //FOR HOLIDAY CHECK BASED ON GENERAL SETTING CHOSSED COMPONENT WISE
			    $emp_comp_value         = $emp_picklist_arr[$employee_code][$holid_label_name];
			   	$holiday_comp_value_arr = explode(",", $holiday_rslt[$att_date]);
			   	$first_half_status      = "-";
			    $second_half_status     = "-";
			  	//DAY STATUS AND STATUS BASED COUNT ADD START FROM DAY TO DAY WITH FORLOOP	
			  	// else
			  	// if($emp_doj > $att_date){
			  	// 	$whole_day_status       = "";
			  	// 	$whole_day_status_val  	= "-";
			  	// 	//$invalid_count = $invalid_count + 1;
			  	// }	
			  	
			  	if(($emp_act_sts === "In Active" or $emp_act_sts === '1') && $emp_resign_date < $att_date){
			  		$whole_day_status       = "";
			  		$whole_day_status_val  	= "-";
			  		//$invalid_count = $invalid_count + 1;
			  	}else
			    if($time_rslt[$employee_code][$att_date]['whole_day_status']){
			    	$whole_day_status      = $time_rslt[$employee_code][$att_date]['whole_day_status'];
			    	$total_work_hours      = $time_rslt[$employee_code][$att_date]['total_work_hours'];
			    	$whole_day_status_val  = $day_status_rslt[$whole_day_status];
			    	$first_half_status     = $time_rslt[$employee_code][$att_date]['first_half_status'];
			    	$second_half_status    = $time_rslt[$employee_code][$att_date]['second_half_status'];
			    	$shift_name            = $time_rslt[$employee_code][$att_date]['shift_name'];
			    	$permission_type       = (int)$time_rslt[$employee_code][$att_date]['permission_type'];
					
					//EXCESS HOURS OT AND SHIFT OT COUNT
					$approved_ot_mins      = (int)$time_rslt[$employee_code][$att_date]['approved_ot_mins'];
					$approved_shift_ot     = (int)$time_rslt[$employee_code][$att_date]['approved_shift_ot'];
					$approved_special_ot   = (int)$time_rslt[$employee_code][$att_date]['approved_special_ot'];
										
					$total_late_hours      = (int)$time_rslt[$employee_code][$att_date]['total_late_hours'];
					//$late_in               = (int)$time_rslt[$employee_code][$att_date]['late_in'];
					$permission            = (int)$time_rslt[$employee_code][$att_date]['total_permission'];
			    	if($approved_ot_mins){
						$excess_ot_mins    = $excess_ot_mins + $approved_ot_mins;		
					}
					if($approved_shift_ot){
						$shift_ot_mins     = $shift_ot_mins + $approved_shift_ot;
					}
					if($approved_special_ot){
						$special_ot_mins   = $special_ot_mins + $approved_special_ot;
					}
					if($approved_ot_mins || $shift_ot_mins || $special_ot_mins){
						$total_ot_mins     = $excess_ot_mins + $shift_ot_mins + $special_ot_mins;
					}
					if($total_late_hours > 0){
						$late_count           = $late_count + 1;						
						$late_mins            = $late_mins + $total_late_hours;			
					}
					if($permission_type === 1){
						$permission_count     = $permission_count + 1;						
						$permission_mins      = $permission_mins  + $permission;
					}
			    	if($present_arr[$whole_day_status]){
			    		$present_count      = $present_count + $present_arr[$whole_day_status];
			    		$present_shift[$employee_code][$shift_name] += $present_arr[$whole_day_status];
			    		if($first_half_status === "FP" && $second_half_status === "SP"){
			    			$first_half_status   = "P";
			    			$second_half_status  = "P";
			    		}
			    		if($first_half_status === "FHL" && $second_half_status === "SHL"){
			    			$absend_count       = $absend_count + 1;
			    		}else
			    		if($first_half_status === "FHL"){	
			    			$absend_count       = $absend_count + 0.5;
			    		}else
			    		if($second_half_status === "SHL"){
			    			$absend_count       = $absend_count + 0.5;
			    		}
			    	}
			    	if($leave_arr[$whole_day_status]){
						if($first_half_status === "ILOP" && $second_half_status === "ILOP"){
							$ilop_count         = $ilop_count +1;
						}
			    		$leave_count        = $leave_count + $leave_arr[$whole_day_status];
			    	}
			    	if($onduty_arr[$whole_day_status]){
			    		$onduty_count       = $onduty_count + $onduty_arr[$whole_day_status];
			    	}
			    	if($mpunch_arr[$whole_day_status]){
			    		$mpunch_count       = $mpunch_count + $mpunch_arr[$whole_day_status];
			    	}
			    	if($unpunch_arr[$whole_day_status]){
			    		$absend_count       = $absend_count + $unpunch_arr[$whole_day_status];
			    		if($unpunch_arr[$whole_day_status] === "U"){
			    			$first_half_status  = "A";
				    		$second_half_status = "A";
				    		$whole_day_status   = "A";
			    		} 
			    	}
			    	if($invalid_arr[$whole_day_status]){
			    		$invalid_count   = $invalid_count + $invalid_arr[$whole_day_status];
			    	}
			    	if($whole_day_status === "H"){
			    		$holiday_count          = $holiday_count + 1; 	
			    	}
			    	if($whole_day_status === "H" && (int)$total_work_hours > 0){
			    		$holiday_work_count       = $holiday_work_count + 1; 	
			    		$holiday_work_mins        = $holiday_work_mins + $total_work_hours; 	
			    	}
			    	if($whole_day_status === "W" && (int)$total_work_hours > 0){
			    		$woff_work_count          = $woff_work_count + 1;
			    		$woff_work_mins           = $woff_work_mins + $total_work_hours;
			    	}
			    	if($weekoff_arr[$whole_day_status]){			    		
			    		$woff_count             = $woff_count + $weekoff_arr[$whole_day_status];
			    	} 
			    }else
			    if($time_wrong_rslt[$employee_code][$att_date]['record_type']){
			    	$whole_day_status_val   = "IP";
			    	$absend_count           = $absend_count + 1;
			    	$first_half_status      = "IP";
			    	$second_half_status     = "IP";
			    }else{
			    	//$invalid_count = $invalid_count + 1;
			    	$whole_day_status_val  	= "-";
			    }
			    
			    if($first_half_status === "U"){
			    	$first_half_status = "A";
			    }
			    if($second_half_status === "U"){
			    	$second_half_status = "A";
			    }
			    //if($this->config->item("db_name") === 'rebar_hrms_db'){ //Only for Rebar
				if($this->config->item("db_name") === 'rebar_hrms_db' || $this->config->item('MANUF') == 1){
					if($this->config->item("db_name") === 'rebar_hrms_db'){
						$food_a       = (int)$time_rslt[$employee_code][$att_date]['food_a'];
						$food_count   = $food_count + $food_a;
					}			    	
			    	$f_shift      = (int)$time_rslt[$employee_code][$att_date]['f_shift'];
			    	$s_shift      = (int)$time_rslt[$employee_code][$att_date]['s_shift'];			    	
			    	$first_count  = $first_count + $f_shift;
			    	$second_count = $second_count + $s_shift;			    	
			    }
			    $tr_head  .= "<th style='text-align:center;'>$att_day</th>";
			    if($first_half_status === $second_half_status){
			    	$tr_line  .= "<td style='text-align:center;'><table><tr><td></td><td>$first_half_status</td><td></td></tr></table></td>";
			    	
			    }else{
			    	$tr_line   .= "<td style='text-align:center;'><table><tr><td>$first_half_status".'</td> <td>|</td><td>'."$second_half_status </td></tr></table></td>";
			    }
			}
			$holiday_work_hours = $this->hours_mins_cal($holiday_work_mins);
			$woff_work_hours    = $this->hours_mins_cal($woff_work_mins);
			$late_hours         = $this->hours_mins_cal($late_mins);
			$permission_hours   = $this->hours_mins_cal($permission_mins);	
			$absend_count       = $absend_count + $ilop_count;	
			$lop_count          = $absend_count + $invalid_count;
			$lop_count          = $lop_count + $lop_count_arr[$employee_code];
			$paid_leave_count   = $paid_count_arr[$employee_code];
			//Prev month ot for rebar
			if($this->config->item("db_name") === 'rebar_hrms_db'){
				$prev_total_ot_mins = (int)$prev_time_rslt[$employee_code]['approved_ot_mins'];
			}
			//Paid Days
			$paid_days_count    = $present_count + $paid_leave_count + $onduty_count + $mpunch_count + $holiday_count + $woff_count;			
			//Total Encash
			$total_encash_count = $leave_encash_count_rslt[$employee_code]['total_encash'];

			$time_comp_head      = "";
			$time_comp_line      = "";
			$total_ot_head       = "";
			$total_ot_line       = "";
			$paid_leave_head     = "";
			$paid_leave_line     = "";
			$shift_count         = 0;	

			//THIS FOR EACH USED TO ADD A CHOOSED TIME OFFICE COMPONENT COUNT
			foreach ($show_time_office_comp_arr as $key => $sts_val){
				$update_qry .= "cw_monthly_input.$key = tbl_posting_temp.$key ,";		   
				if($sts_val === "P"){
			    	$time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
			    	$time_comp_line        .= "<td style='text-align:center;'>$present_count</td>";
			    	$posting_value         .= ',"'.$present_count.'"';
			    	$posting_qry           .= ','.$key;
			    }else
			    if($sts_val === "A"){
			    	$time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
			    	$time_comp_line        .= "<td style='text-align:center;'>$absend_count</td>";
			    	$posting_value         .= ',"'.$absend_count.'"';
			    	$posting_qry           .= ','.$key;
			    }else
			    if($sts_val === "L"){
			    	$time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
			    	$time_comp_line        .= "<td style='text-align:center;'>$leave_count</td>";
			    	$posting_value         .= ',"'.$leave_count.'"';
			    	$posting_qry           .= ','.$key;
			    }else
			    if($sts_val === "OD"){
			    	$time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
			    	$time_comp_line        .= "<td style='text-align:center;'>$onduty_count</td>";
			    	$posting_value         .= ',"'.$onduty_count.'"';
			    	$posting_qry           .= ','.$key;
			    }else
			    if($sts_val === "M"){
			    	$time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					$time_comp_line        .= "<td style='text-align:center;'>$mpunch_count</td>";
					$posting_value         .= ',"'.$mpunch_count.'"';
					$posting_qry           .= ','.$key;
			    }else
			    if($sts_val === "I"){
			    	$time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
			    	$time_comp_line        .= "<td style='text-align:center;'>$invalid_count</td>";
			    	$posting_value         .= ',"'.$invalid_count.'"';
			    	$posting_qry           .= ','.$key;
			    }else
			    if($sts_val === "H"){
				    $time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					$time_comp_line        .= "<td style='text-align:center;'>$holiday_count</td>";
					$posting_value         .= ',"'.$holiday_count.'"';
					$posting_qry           .= ','.$key;
			    }else
			    if($sts_val === "holiday_working"){ 
				    $time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					$time_comp_line        .= "<td style='text-align:center;'>$holiday_work_count</td>";
					$posting_value         .= ',"'.$holiday_work_count.'"';
					$posting_qry           .= ','.$key;
			    }else
			    if($sts_val === "holiday_work_hours"){
				    $time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					$time_comp_line        .= "<td style='text-align:center;'>$holiday_work_hours</td>";
					$posting_value         .= ',"'.$holiday_work_hours.'"';
					$posting_qry           .= ','.$key;
			    }else
			    if($sts_val === "holiday_work_mins"){
				    $time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					$time_comp_line        .= "<td style='text-align:center;'>$holiday_work_mins</td>";
					$posting_value         .= ',"'.$holiday_work_mins.'"';
					$posting_qry           .= ','.$key;
			    }else
			    if($sts_val === "W"){
				    $time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					$time_comp_line        .= "<td style='text-align:center;'>$woff_count</td>";
					$posting_value         .= ',"'.$woff_count.'"';
					$posting_qry           .= ','.$key;
			    }else
			    if($sts_val === "weekoff_working"){
				    $time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					$time_comp_line        .= "<td style='text-align:center;'>$woff_work_count</td>";
					$posting_value         .= ',"'.$woff_work_count.'"';
					$posting_qry           .= ','.$key;
			    }else 
			    if($sts_val === "woff_work_hours"){
				    $time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					$time_comp_line        .= "<td style='text-align:center;'>$woff_work_hours</td>";
					$posting_value         .= ',"'.$woff_work_hours.'"';
					$posting_qry           .= ','.$key;
			    }else
			    if($sts_val === "woff_work_mins"){
				    $time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					$time_comp_line        .= "<td style='text-align:center;'>$woff_work_mins</td>";
					$posting_value         .= ',"'.$woff_work_mins.'"';
					$posting_qry           .= ','.$key;
			    }else
			    if($sts_val === "late_days"){
				    $time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					$time_comp_line        .= "<td style='text-align:center;'>$late_count</td>";
					$posting_value         .= ',"'.$late_count.'"';
					$posting_qry           .= ','.$key;
			    }else 
			    if($sts_val === "late_hours"){
				    $time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					$time_comp_line        .= "<td style='text-align:center;'>$late_hours</td>";
					$posting_value         .= ',"'.$late_hours.'"';
					$posting_qry           .= ','.$key;
			    }else
			    if($sts_val === "late_mins"){
				    $time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					$time_comp_line        .= "<td style='text-align:center;'>$late_mins</td>";
					$posting_value         .= ',"'.$late_mins.'"';
					$posting_qry           .= ','.$key;
			    }else
			    if($sts_val === "perm_days"){
				    $time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					$time_comp_line        .= "<td style='text-align:center;'>$permission_count</td>";
					$posting_value         .= ',"'.$permission_count.'"';
					$posting_qry           .= ','.$key;
			    }else 
			    if($sts_val === "perm_hours"){
				    $time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					$time_comp_line        .= "<td style='text-align:center;'>$permission_hours</td>";
					$posting_value         .= ',"'.$permission_hours.'"';
					$posting_qry           .= ','.$key;
			    }else
			    if($sts_val === "perm_mins"){
				    $time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					$time_comp_line        .= "<td style='text-align:center;'>$permission_mins</td>";
					$posting_value         .= ',"'.$permission_mins.'"';
					$posting_qry           .= ','.$key;
			    }else
				if($sts_val === "excess_ot"){
					$excess_ot_head         = "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					//function for get a total hours and minutes 
					$excess_ot_hrs          = $this->hours_mins_cal($excess_ot_mins);    
					$excess_ot_line         = "<td style='text-align:center;'>$excess_ot_hrs</td>";
					$posting_value         .= ',"'.$excess_ot_mins.'"';
					$posting_qry           .= ','.$key;
				}else
				if($sts_val === "shift_ot"){
					$shift_ot_head          = "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					//function for get a total hours and minutes 
					$shift_ot_hrs           = $this->hours_mins_cal($shift_ot_mins);    
					$shift_ot_line          = "<td style='text-align:center;'>$shift_ot_hrs</td>";
					$posting_value         .= ',"'.$shift_ot_hrs.'"';
					$posting_qry           .= ','.$key;
				}else
				if($sts_val === "special_ot"){
					$special_ot_head   = "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					//function for get a total hours and minutes 
					$special_ot_hrs    = $this->hours_mins_cal($special_ot_mins);    
					$special_ot_line   = "<td style='text-align:center;'>$special_ot_hrs</td>";
					$posting_value    .= ',"'.$special_ot_hrs.'"';
					$posting_qry      .= ','.$key;
				}else
				if($sts_val === "total_ot"){
					$total_ot_head     = "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					//function for get a total hours and minutes 
					$total_ot_hrs      = $this->hours_mins_cal($total_ot_mins);    
					$total_ot_line     = "<td style='text-align:center;'>$total_ot_hrs</td>";
					/*if($total_ot_mins > $max_ot_mins){
						$final_mins    = $max_ot_mins; //$total_ot_mins - 
						$total_ot_hrs  = $this->hours_mins_cal($final_mins);
					}*/
					$posting_value    .= ',"'.$total_ot_hrs.'"';
					$posting_qry           .= ','.$key;
				}else
				if($sts_val === "prev_total_ot"){
					$total_ot_head     .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
					//function for get a total hours and minutes 
					$total_ot_hrs      = $this->hours_mins_cal($prev_total_ot_mins);    
					$total_ot_line     .= "<td style='text-align:center;'>$total_ot_hrs</td>";
					/*if($prev_total_ot_mins > $max_ot_mins){
						$final_mins    = $max_ot_mins; //$total_ot_mins - 
						$total_ot_hrs  = $this->hours_mins_cal($final_mins);
					}*/
					$posting_value    .= ',"'.$total_ot_hrs.'"';
					$posting_qry           .= ','.$key;
				}else
				if($sts_val === "prev_total_ot_mins"){
					$total_ot_head     .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";   
					$total_ot_line     .= "<td style='text-align:center;'>$prev_total_ot_mins</td>";
					/*if($prev_total_ot_mins > $max_ot_mins){
						$prev_total_ot_mins = $max_ot_mins;
					}*/
					$posting_value    .= ',"'.$prev_total_ot_mins.'"';
					$posting_qry      .= ','.$key;
				}else
				if($sts_val === "paid_leave"){
					$paid_leave_head   .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
				    $paid_leave_line   .= "<td style='text-align:center;'>$paid_leave_count</td>";
				    $posting_value    .= ',"'.$paid_leave_count.'"';
				    $posting_qry           .= ','.$key;		
				}else
				if($sts_val === "lop_days"){
					//Total LOP
					$paid_leave_head   .= "<th>Total Lop Days</th>";
				    $paid_leave_line   .= "<td style='text-align:center;'>$lop_count</td>";
				    $posting_value    .= ',"'.$lop_count.'"';
				    $posting_qry           .= ','.$key;				    		
				}else
				if($sts_val === "paid_days"){
					$paid_head   = "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
				    $paid_line   = "<td style='text-align:center;'>$paid_days_count</td>";
				    $posting_value    .= ',"'.$paid_days_count.'"';
				    $posting_qry           .= ','.$key;		
				}else
				if($sts_val === "total_encash"){
					$paid_leave_head   .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
				    $paid_leave_line   .= "<td style='text-align:center;'>$total_encash_count</td>";
				    $posting_value    .= ',"'.$total_encash_count.'"';
				    $posting_qry           .= ','.$key;		
				}else
				if($sts_val === "food_count"){
					$time_comp_head   .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
				    $time_comp_line   .= "<td style='text-align:center;'>$food_count</td>";
				    $posting_value    .= ',"'.$food_count.'"';
				    $posting_qry           .= ','.$key;		
				}else
				if($sts_val === "1st_count"){
					$time_comp_head   .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
				    $time_comp_line   .= "<td style='text-align:center;'>$first_count</td>";
				    $posting_value    .= ',"'.$first_count.'"';
				    $posting_qry           .= ','.$key;		
				}else
				if($sts_val === "2nd_count"){
					$time_comp_head   .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
				    $time_comp_line   .= "<td style='text-align:center;'>$second_count</td>";
				    $posting_value    .= ',"'.$second_count.'"';
				    $posting_qry           .= ','.$key;		
				}else
				if($sts_val === "n_count"){
					$time_comp_head   .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
				    $time_comp_line   .= "<td style='text-align:center;'>$n_count</td>";
				    $posting_value    .= ',"'.$n_count.'"';
				    $posting_qry           .= ','.$key;		
				}else{
			    	if($shift_master_rslt[$employee_code][$sts_val]){		    		
			    		if($present_shift[$employee_code][$sts_val]){
			    			$shift_count        = $present_shift[$employee_code][$sts_val];
			    		}else{
			    			$shift_count        = 0;
			    		}
			    		$time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
			    		$time_comp_line        .= "<td style='text-align:center;'>$shift_count</td>";
			    		$posting_value         .= ',"'.$shift_count.'"';
			    		$posting_qry           .= ','.$key;
			    	}else
			    	if($leave_count_arr[$employee_code][$sts_val]['leave_count']){
			    		$time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
		    			$leave_name_count       = $leave_count_arr[$employee_code][$sts_val]['leave_count'];
			    		$time_comp_line        .= "<td style='text-align:center;'>$leave_name_count</td>";
			    		$posting_value         .= ',"'.$leave_name_count.'"';
			    		$posting_qry           .= ','.$key;
						//PAID LEAVE COUNT FOR EMPLOYEE WISE BASED ON LEAVE CREATION MODULE IN PAID LEAVE CREATION BASED 
						/*if((int)$leave_count_arr[$employee_code][$sts_val]['paid_leave'] === 1){
							$paid_leave_count       = $paid_leave_count + $leave_count_arr[$employee_code][$sts_val]['leave_count'];
						}*/
			    	}else
			    	if($leave_bal_arr[$employee_code][$sts_val]){
			    		$time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
		    			$leave_bal_count       = $leave_bal_arr[$employee_code][$sts_val];
			    		$time_comp_line        .= "<td style='text-align:center;'>$leave_bal_count</td>";
			    		$posting_value         .= ',"'.$leave_bal_count.'"';
			    		$posting_qry           .= ','.$key;
			    	}else 
			    	if($opening_leave_arr[$employee_code][$sts_val]){
			    		$time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
		    			$leave_op_count         = $opening_leave_arr[$employee_code][$sts_val];
			    		$time_comp_line        .= "<td style='text-align:center;'>$leave_op_count</td>";
			    		$posting_value         .= ',"'.$leave_op_count.'"';
			    		$posting_qry           .= ','.$key;
			    	}else
			    	if($leave_encash_count_rslt[$employee_code][$sts_val]){
			    		$time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
		    			$leave_name_count       = $leave_encash_count_rslt[$employee_code][$sts_val];
			    		$time_comp_line        .= "<td style='text-align:center;'>$leave_name_count</td>";
			    		$posting_value         .= ',"'.$leave_name_count.'"';
			    		$posting_qry           .= ','.$key;

						//TOTAL ENCASH COUNT						
			    		$total_encash_count     = $total_encash_count + $leave_name_count;
			    	}else{			    		
			    		if($all_time_office_comp_arr[$sts_val]){
			    			$time_comp_head        .= "<th>".$all_time_office_comp_arr[$sts_val]."</th>";
			    			$time_comp_line        .= "<td style='text-align:center;'>0</td>";
			    			$posting_value         .= ',"0"';
			    			$posting_qry           .= ','.$key;
			    		}
			    	}
			    }			    			   
			}								
			$tr_head      .= "$time_comp_head <th>Total Encash</th> $excess_ot_head $shift_ot_head $special_ot_head $total_ot_head $paid_leave_head $lop_head $paid_head</tr>";
			$tr_line      .= "$time_comp_line <td style='text-align:center;'>$total_encash_count</td> $excess_ot_line $shift_ot_line $special_ot_line $total_ot_line $paid_leave_line $lop_line $paid_line </tr>";
			$posting_value    .= '),';
		}
		if($from === 'report'){
			$table_content = "<table class='table table-striped table-bordered' id='muster_report' style='width:100%;border:1px solid #000;'>
						<thead>
							$tr_head
						</thead>
						<tbody>
							$tr_line
						</tbody>
					</table>";
			return $table_content; 
		}else{
			$drop_qry  = 'DROP TABLE IF EXISTS tbl_posting_temp';
			$this->db->query("CALL sp_a_run ('RUN','$drop_qry')");

			$temp_qry  = 'CREATE TABLE tbl_posting_temp SELECT '.$posting_qry.' FROM cw_monthly_input LIMIT 0';			
			$this->db->query("CALL sp_a_run ('RUN','$temp_qry')");
			//Insert Data into temp table
			$insert_qry = 'INSERT INTO tbl_posting_temp('.$posting_qry.') VALUES '.rtrim($posting_value,",");
			$this->db->query($insert_qry);

			$exist_qry   = 'select count(*) as exist_count from cw_monthly_input where cw_monthly_input.trans_status =1 and role = "'.$category.'" and process_month = "'.$process_month.'"';
	        $exist_info  = $this->db->query("CALL sp_a_run ('SELECT','$exist_qry')");
	        $exist_rslt  = $exist_info->result();
	        $exist_info->next_result();
	        $exist_count = $exist_rslt[0]->exist_count;

	        if((int)$exist_count > 0){
				$missed_emp_qry  = 'select GROUP_CONCAT(employee_code) as employee_codes from cw_employees where cw_employees.trans_status = 1 and DATE_FORMAT(cw_employees.date_of_joining, "%Y-%m-%d") <= "' . $end_date . '" and (cw_employees.termination_status = 0 or DATE_FORMAT(cw_employees.last_working_date, "%Y-%m-%d") >= "' . $start_date . '") and role = "' . $category . '" and employee_code not in(SELECT employee_code from cw_monthly_input WHERE cw_monthly_input.trans_status = 1 and cw_monthly_input.process_month = "' . $process_month . '" and role = "' . $category . '")';
				$missed_emp_data = $this->db->query("CALL sp_a_run ('SELECT','$missed_emp_qry')");
				$missed_emp_rslt = $missed_emp_data->result();
				$missed_emp_data->next_result();
				$missed_emp  = '"'.str_replace(',', '","', $missed_emp_rslt[0]->employee_codes).'"';
				if($missed_emp_rslt){
					$insert_missed_qry = 'INSERT INTO cw_monthly_input ('.$posting_qry.',trans_created_by,trans_created_date) SELECT '.$posting_qry.','.$this->logged_id.',"'.date("Y-m-d H:i:s").'" from tbl_posting_temp where employee_code in('.$missed_emp.')';
					$this->db->query("CALL sp_a_run ('RUN','$insert_missed_qry')");
				}
	        	if($update_qry){
	        		$update_qry = 'UPDATE cw_monthly_input INNER JOIN tbl_posting_temp ON tbl_posting_temp.employee_code = cw_monthly_input.employee_code AND tbl_posting_temp.process_month = cw_monthly_input.process_month SET '.rtrim($update_qry,",").' where cw_monthly_input.process_month = "' . $process_month . '" and cw_monthly_input.payroll_status != 1';
					$update_info = $this->db->query("CALL sp_a_run ('UPDATE','$update_qry')");
	        	}	        	
	        }else{
	        	$insert_mi_qry = 'INSERT INTO cw_monthly_input ('.$posting_qry.',trans_created_by,trans_created_date) SELECT '.$posting_qry.','.$this->logged_id.',"'.date("Y-m-d H:i:s").'" from tbl_posting_temp ';
				$update_info = $this->db->query("CALL sp_a_run ('RUN','$insert_mi_qry')");
	        }
	        if($update_info){
	        	 //Check Previous month tabe data exist Start
		        $previous_column_qry = 'SELECT GROUP_CONCAT(CONCAT("cw_monthly_input.",previous_column, "=cw_transactions.", matching_column)) AS update_columns FROM cw_monthly_input_previous where cw_monthly_input_previous.trans_status=1';
		        $previous_column_data   = $this->db->query("CALL sp_a_run ('SELECT','$previous_column_qry')");
		        $previous_column_result = $previous_column_data->result();
		        $previous_column_data->next_result();
		        $previous_column_count = (int) $previous_column_data->num_rows();
		        if($previous_column_count > 0){
		            $update_columns = $previous_column_result[0]->update_columns;
		            $last_month     = date("m-Y", strtotime( '-1 month' , strtotime ("01-$process_month")));                    
		            //Check previous month data exist
		            $trans_exist_qry  = 'select employee_code from cw_transactions where  trans_status = 1 and transactions_month = "' . $last_month . '" '.$trans_query.' and termination_status = 0 limit 0,1';
		            $trans_exist_data = $this->db->query("CALL sp_a_run ('SELECT','$trans_exist_qry')");
		            $trans_exist_data->result();
		            $trans_exist_data->next_result();
		            $trans_exist_count = (int) $trans_exist_data->num_rows();
		            if ($trans_exist_count > 0) {
		                //GET Previous transaction data of matching column
		                if ($update_columns){
		                    $get_previous_val_qry = 'UPDATE cw_monthly_input
		                    INNER JOIN  cw_transactions ON cw_monthly_input.employee_code = cw_transactions.employee_code
		                    SET ' . $update_columns . '
		                    WHERE cw_transactions.trans_status=1 and cw_monthly_input.input_status = 0 and cw_transactions.transactions_month = "' . $last_month . '" '.$trans_query;
		                    $this->db->query("CALL sp_a_run ('UPDATE','$get_previous_val_qry')");
		                }
		            }    
		        }
		        $ret_rslt =  $this->update_supplymentry($supp_query,$process_month);
		        if($ret_rslt){
		        	return true;
		        }else{
		        	return false;
		        }	        	
	        }else{
	        	return false;
	        }
		}		
	}
	//Update Supplementry
	public function update_supplymentry($supp_query,$search_month){
		$back_month_date = "01-".$search_month;
		$back_month = date("m-Y", strtotime("-1 month", strtotime($back_month_date)));
		$supplymentry_sts_qry = 'select count(*) as rslt_count from cw_monthly_input where process_month="'.$back_month.'" and supplementary_status = 1 and trans_status = 1';
		$supplymentry_sts_data   = $this->db->query("CALL sp_a_run ('SELECT','$supplymentry_sts_qry')");
		$supplymentry_sts_result = $supplymentry_sts_data->result();
		$supplymentry_sts_data->next_result();
		$supply_mi_count = $supplymentry_sts_result[0]->rslt_count;
		
		$supplymentry_exit_qry = 'select count(*) as supply_count from cw_supplementary_detail where supplementary_month = "'.$search_month.'" '.$supp_query.' and trans_status = 1';
		$supplymentry_data   = $this->db->query("CALL sp_a_run ('SELECT','$supplymentry_exit_qry')");
		$supplymentry_result = $supplymentry_data->result();
		$supplymentry_data->next_result();
		$supply_exit_count  = $supplymentry_result[0]->supply_count;
		if((int)$supply_mi_count > 0){
			if((int)$supply_exit_count > 0){
				$get_supplymentry_qry = 'select IFNULL(sum(supp_month_days),0) as supp_month_days,IFNULL(sum(supp_paid_days),0) as supp_paid_days,emp_code from cw_supplementary_detail inner join cw_monthly_input on cw_monthly_input.employee_code =cw_supplementary_detail.emp_code where cw_monthly_input.trans_status=1 and cw_supplementary_detail.supplementary_month="'.$search_month.'" '.$supp_query.' and supplementary_status = 1 group by emp_code';
				$get_supplymentry_data   = $this->db->query("CALL sp_a_run ('SELECT','$get_supplymentry_qry')");
				$get_supplymentry_result = $get_supplymentry_data->result();
				$get_supplymentry_data->next_result();
				$update_on = date("Y-m-d H:i:s");
				if(!empty($get_supplymentry_result)){
					foreach($get_supplymentry_result as $sup_rslt){
						$emp_code        = $sup_rslt->emp_code;
						$supp_paid_days  = $sup_rslt->supp_paid_days;
						$supp_month_days = $sup_rslt->supp_month_days;
						$upd_mi_query = 'UPDATE cw_monthly_input SET supplementary_day ="'.$supp_paid_days.'", supplementary_month ="'.$supp_month_days.'", trans_updated_by = "'.$this->logged_id.'",trans_updated_date = "'.$update_on.'" WHERE process_month="'.$search_month.'" and cw_monthly_input.input_status = 0 '.$supp_query.' and trans_status=1 ';
						$this->db->query("CALL sp_a_run ('UPDATE','$upd_mi_query')");
					}
				}
			}
		}
		return true;
	}

	/*THIS FUNCTION ADD BY ANDREWS*/
		//Coff Validation common for Overtime request and approval
	public function compoff_validation($employee_code,$category,$approved_over_time,$ot_type){
		//Get Active Salary Date that need to be process payroll
		$active_salary_date = $this->get_tos_active_salary_date();
		$salary_start_date = $active_salary_date[$category]['salary_start_date'];
		$salary_end_date   = $active_salary_date[$category]['salary_end_date'];
		if((int)$ot_type === 4){
			$check_inp_result = $this->get_coff_settings($employee_code,$category);
			if($check_inp_result){
				$coff_activated = $check_inp_result[0]->coff_activated;		
				$max_ot_hours   = $check_inp_result[0]->max_ot_hours;
				$halfday_min    = $check_inp_result[0]->halfday_min;
				$ot_activated   = $check_inp_result[0]->ot_activated;
				$halfday_hours  = $this->hours_mins_cal($halfday_min);
				$fullday_min    = $check_inp_result[0]->fullday_min;
				$max_ot_mins    = $this->hourstomins($max_ot_hours);
				if((int)$coff_activated === 1){
					$excess_work_mins    = $this->hourstomins($approved_over_time);			
					//Check Hours reached Half Day
					if($excess_work_mins < $halfday_min){
						echo json_encode(array('success' => FALSE, 'message' => "Minimum $halfday_hours Hrs are mandatory for requesting C-Off"));
						exit(0);
					}
					//Get Shift Overtime record //approved_shift_ot+
					$shift_qry    = 'SELECT SUM(approved_ot_mins+approved_special_ot) as shiftot_mins from cw_time_entry where employee_code = "'.$employee_code.'" and att_date BETWEEN "'.$salary_start_date.'" and "'.$salary_end_date.'"';
					$shift_info   = $this->db->query("CALL sp_a_run ('SELECT','$shift_qry')");
					$shift_result = $shift_info->result();
					$shift_info->next_result();
					$final_ot_mins = (int)$shift_result[0]->shiftot_mins; 
					if($max_ot_mins > $final_ot_mins){
						echo json_encode(array('success' => FALSE, 'message' => "Total OT Hours in this month yet to reach your Max OT Hours($max_ot_hours)... Please Apply Overtime"));
						exit(0);
					}
					//CHECK EXIST COUNT IN OVERTIME ENTRY TABLE
					$coff_exist_qry    = 'select count(prime_coff_entry_id) as count from cw_coff_entry where cw_coff_entry.employee_code = "'.$employee_code.'" and cw_coff_entry.credited_date  = "'.$entry_date.'"';
					$coff_exist_info   = $this->db->query("CALL sp_a_run ('SELECT','$coff_exist_qry')");
					$coff_exist_rslt   = $coff_exist_info->result();
					$coff_exist_info->next_result();
					$coff_exist_count  = (int)$coff_exist_rslt[0]->count;
					if($coff_exist_count){
						echo json_encode(array('success' => FALSE, 'message' => "This Request Already Exist? Please Check it.!"));
						exit(0);
					}						
				}else{
					echo json_encode(array('success' => FALSE, 'message' => "C-off Not Activated... Please Apply Overtime"));
					exit(0);
				}
			}
						
		}else{
			if((int)$ot_activated === 1){
				$ot_entry_qry    = 'SELECT SUM(CASE WHEN approval_status = 2 THEN TIME_TO_SEC(over_time)/60 END) AS approved_ot,SUM(CASE WHEN approval_status = 1 THEN TIME_TO_SEC(excess_work)/60 END) AS pending_ot from cw_overtime_entry where employee_code = "'.$employee_code.'" and entry_date BETWEEN "'.$salary_start_date.'" and "'.$salary_end_date.'"';
				$ot_entry_info   = $this->db->query("CALL sp_a_run ('SELECT','$ot_entry_qry')");
				$ot_entry_result = $ot_entry_info->result();
				$ot_entry_info->next_result();
				$approved_ot     = $ot_entry_result[0]->approved_ot;
				$pending_ot      = $ot_entry_result[0]->pending_ot;
				$ex_work_mins    = $this->hourstomins($approved_over_time);
				$total_ot_mins   = $approved_ot + $pending_ot + $ex_work_mins;
				if($max_ot_mins < $total_ot_mins){
					echo json_encode(array('success' => FALSE, 'message' => "Oops.. Already Reached Your Max OT Hours($max_ot_hours)..."));
					exit(0);
				}
			}else
			if((int)$ot_activated === 2){
				echo json_encode(array('success' => FALSE, 'message' => "Overtime Not Activated.."));
				exit(0);
			}
		}		
	}

	//Monthly Off Validation
	public function check_moff_exist($employee_code,$from_date,$to_date){
		$moff_entry_qry      = 'select SUM(balance_count) as moff_count from cw_moff_entry where employee_code = "'.$employee_code.'" and "'.$from_date.'" >= cr_date and "'.$to_date.'" <= end_date and trans_status = 1 and moff_status = 1';
		$moff_entry_info     = $this->db->query("CALL sp_a_run ('SELECT','$moff_entry_qry')");
		$moff_entry_result   = $moff_entry_info->result();
		$moff_entry_info->next_result();
		$moff_count    = $moff_entry_result[0]->moff_count;
		if(!$moff_count){
			$moff_count = 0;
		}
		return $moff_count;
	}

  public function get_coff_settings($employee_code,$category){
		$company_info       = $this->company_info();
		$coff_based_on      = $company_info[0]->coff_based_on; //Get from company info module.
		if(!$coff_based_on){
			echo json_encode(array('success' => FALSE, 'message' => "Please set coff based on input in timeoffice setting.."));
			exit(0);
		}
		$coff_check_qry     = "";
		if($coff_based_on !== 'role' && $coff_based_on !== '0'){
			$emp_pick_arr   = $this->get_emp_data();
			$coff_check_val = $emp_pick_arr[$employee_code][$coff_based_on];
			if(!$coff_check_val){
				echo json_encode(array('success' => FALSE, 'message' => "Check input not exist for this Employee.."));
						exit(0);
			}
			$coff_check_qry = ' and FIND_IN_SET('.$coff_check_val.', cw_coff_settings.check_input)';
		}
		$check_inp_qry      = 'SELECT * from cw_coff_settings where FIND_IN_SET('.$category.', cw_coff_settings.category) '.$coff_check_qry;
		$check_inp_info     = $this->db->query("CALL sp_a_run ('SELECT','$check_inp_qry')");
		$check_inp_result   = $check_inp_info->result();
		$check_inp_info->next_result();	
		return $check_inp_result;
	}
	//prev view inputs
	public function get_previous_view($form_id){
		if($this->control_name === 'monthly_input' || $this->control_name === 'employee_self_portal'){
			$control_name = 'employees';
		}else{
			$control_name = $this->control_name;
		}
		$table_name   	  = "cw_".$control_name;
		$prime_table_id   = "prime_".$control_name."_id";
		$column_query = 'select label_name,default_value from cw_form_setting  where prime_module_id = "'.$control_name.'" and field_show = "1" and input_view_type in(1,2) and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",user_right_for) ORDER BY input_for,field_sort asc';
		$column_info   = $this->db->query("CALL sp_a_run ('SELECT','$column_query')");
		$column_rslt   = $column_info->result();
		$column_info->next_result();
		$column_name   = array_column($column_rslt,'label_name');
		$default_value = array_column($column_rslt,'default_value');
		$form_result   = array();
		if($column_name){
			if((int)$form_id === 0){
				$form_result[0] = array_combine($column_name ?? [], $default_value  ?? []);			
			}else{
				$from_query  = 'select '.implode(",",$column_name ?? []).' from '.$table_name.' where '.$table_name.'.trans_status = 1 and '.$table_name.'.'.$prime_table_id.' = '.$form_id.' ';	
				$form_data   = $this->db->query("CALL sp_a_run ('SELECT','$from_query')");
				$form_result = $form_data->result_array();
				$form_data->next_result();			
			}			
		}			
		return $form_result;
	}

	public function gen_setting_comp_info(){
		$get_components = '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')");
		$get_components_result = $get_components_info->result();
		$get_components_info->next_result();
		$components[""]        = "---- Select Component ----";
		foreach($get_components_result as $component){
			$prime_form_id     = $component->prime_form_id;
			$components_name   = $component->label_name;
			$components[$this->xss_clean($prime_form_id)] = $this->xss_clean($components_name);		
		}
		return $components;
	}

	//DR ALL SHIFT MASTER SHIFT DETAILS SHOULD MAP IN PERMISSION SETTING MODULE CHECK 3NOV22 START
	public function shift_permission_set_check(){
		$error_shift      = '';
		$shift_mas_qry    = 'select prime_shift_master_id,shift_name from cw_shift_master where cw_shift_master.trans_status = 1';	
		$shift_mas_info   = $this->db->query("CALL sp_a_run ('SELECT','$shift_mas_qry')");
		$shift_mas_rslt   = $shift_mas_info->result_array();
		$shift_mas_info->next_result();
		
		$shift_mas_arr    = array_reduce($shift_mas_rslt, function ($result, $arr) {
			$result[$arr['prime_shift_master_id']]= $arr['prime_shift_master_id'];
			return $result;
		}, array());

		$shift_name_arr   = array_reduce($shift_mas_rslt, function ($result, $arr) {
			$result[$arr['prime_shift_master_id']]= $arr['shift_name'];
			return $result;
		}, array());	

		$perm_set_qry     = 'SELECT shift_name FROM `cw_permission_setting` WHERE `trans_status` = 1';	
		$perm_set_info    = $this->db->query("CALL sp_a_run ('SELECT','$perm_set_qry')");
		$perm_set_rslt    = $perm_set_info->result_array();
		$perm_set_info->next_result();

		$perm_set_arr     = array_flip(array_reduce(array_reduce($perm_set_rslt, function ($result, $arr) {
			$result[]     = explode(",",$arr['shift_name']);
			return $result;
		}, array()), 'array_merge', array()));

		$diff_shift_arr   = array_diff_key($shift_mas_arr,$perm_set_arr);
		$error_shift_arr  = array_intersect_key($shift_name_arr,$diff_shift_arr);
		$error_shift      = implode(',',$error_shift_arr ?? []);
		return $error_shift;
	}
	//DR ALL SHIFT MASTER SHIFT DETAILS SHOULD MAP IN PERMISSION SETTING MODULE CHECK 3NOV22 END
	public function unix_convertion($excel_date){
		$unix_date  = ((int)$excel_date - 25569) * 86400;
		$excel_date = 25569 + ($unix_date / 86400);
		$unix_date  = ((int)$excel_date - 25569) * 86400;
		return $unix_date;
	}
	public function column_mapping(){
		//get Payroll Function Map array
		$get_map_qry 		= 'select * from cw_payroll_function_map where trans_status=1';
		$get_map_info   	= $this->db->query("CALL sp_a_run ('SELECT','$get_map_qry')");
		$get_map_rslt 		= $get_map_info->result_array();
		$get_map_info->next_result();
		$this->get_map_arr = array_reduce($get_map_rslt, function ($result, $arr) {
			$result[$arr['loc_name']] = $arr['db_column'];
			return $result;
		}, array());
	}
	//SELECT QUERY BUILD FUNCTION FOR PAY STRUCTURE
	public function query_build_function($select_columns,$table_name,$table_join,$table_where){
		$table_qry_detail  = 'select '.$select_columns.' from '.$table_name.' '.$table_join.' where '.$table_where.'';
		$table_qry_info    = $this->db->query("CALL sp_a_run ('SELECT','$table_qry_detail')");
		$table_qry_rslt    = $table_qry_info->result_array();
		$table_qry_info->next_result();
		return $table_qry_rslt;
	}
	//INSERT QUERY BUILD FUNCTION FOR PAY STRUCTURE
	public function query_ins_function($table_name,$table_col,$table_val,$table_where){
		$ins_qry_detail   = 'INSERT INTO '.$table_name.'('.$table_col.') VALUES '.$table_val.' '.$table_where.'';
		$ins_qry_info     = $this->db->query("CALL sp_a_run ('INSERT','$ins_qry_detail')");
		$ins_qry_rslt     = $ins_qry_info->result();
		$ins_qry_info->next_result();
		return $ins_qry_rslt;
	}
	//dependent dropdown form function
	public function dependent_data_set(){
		$prime_module_id       =  $this->input->post("prime_module_id");
		$depen_select_val      =  $this->input->post("depen_select");
		$depen_pick_input      =  $this->input->post("depen_pick_input");
		$table_column1         =  $this->input->post("table_column1");
		$table_column2         =  $this->input->post("table_column2");
		$label_name            =  $this->input->post("label_id");
		$pick_table            =  $this->input->post("pick_table");
		$pick_list             =  $this->input->post("pick_list");
		$pick_display          =  $this->input->post("pick_display_val");

		$picklist_table_qry    = 'select pick_list,pick_table,prime_form_id,label_name from cw_form_setting where prime_module_id = "'.$prime_module_id.'" and label_name in ("'.$depen_pick_input.'","'.$label_name.'") and trans_status = 1';
		$picklist_table_data   = $this->db->query("CALL sp_a_run ('SELECT','$picklist_table_qry')");
		$picklist_table_rslt   = $picklist_table_data->result_array();
		$picklist_table_data->next_result();
		$picklist_table_rslt   = array_reduce($picklist_table_rslt, function($result, $arr){	
			$result[$arr['label_name']] = $arr;
			return $result;
		}, array());
		$depen_pick_table      = $picklist_table_rslt[$depen_pick_input]['pick_table'];

		$pick_list_val         = explode(",",$pick_list);
		$pick_list_val_1       = $pick_list_val[0];
		$pick_list_val_2       = $pick_list_val[1];
		if($pick_display){
			$pick_list         = "$pick_table.$pick_list_val_1,CONCAT_WS(\" - \", $pick_table.$pick_display) as $pick_list_val_2";
		}
		//FOR ROLE BASED WHERE CONDTION ADD
		$where_condition       = $this->get_role_based_picklist($picklist_table_rslt[$label_name]['prime_form_id'],$prime_module_id);

		$pick_query  = "select $pick_list from $pick_table inner join $depen_pick_table on $depen_pick_table.$table_column1 = $pick_table.$table_column2 where $depen_pick_table.$table_column1 = \"$depen_select_val\" and $pick_table.trans_status = 1 and $depen_pick_table.trans_status = 1 $where_condition";
		$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  ?? []);
		}
		$drop_list = "<option value=''>$label_name</option>";
		foreach($final_pick as $key => $val){
			$drop_list .= "<option value='$key'>$val</option>";
		}
		echo $drop_list;
	}
	//fetch data auto picklist
	public function fetch_picklist(){
		$depand_lab_val	= implode('","', $this->input->post("depand_lab_val") ?? []);
		$label_id 		= $this->input->post("label_id");
		$label_value 	= $this->input->post("label_value");
		$prime_form_id 	= $this->input->post("prime_form_id");
		$form_query  = 'select * from cw_form_setting where prime_form_id in ("'.$depand_lab_val.'","'.$prime_form_id.'")';
		$form_data   = $this->db->query("CALL sp_a_run ('SELECT','$form_query')");
		$form_result = $form_data->result_array();
		$form_data->next_result();	
		$form_result = array_reduce($form_result, function($result, $arr){	
			$result[$arr['label_name']] = $arr;
			return $result;
		}, array());
		$form_result_arr 	= $form_result;
		unset($form_result_arr[$label_id]);
		$dropdown_list	= array();
		foreach ($form_result_arr as $key => $form_for) {
			$field_type 	= $form_for['field_type'];
			if((int)$field_type === 5){
				$label_name 	= $form_for['label_name'];
				$pick_list 		= $form_for['pick_list'];
				$pick_table 	= $form_for['pick_table'];
				$table_column1 	= $form_for['table_column1'];
				$table_column2 	= $form_for['table_column2'];
				$dependent_pick	= $form_for['dependent_pick_input'];
				$pick_display   = $form_for['pick_display_value'];
				$pick_list_arr 	= explode(',', $pick_list);
				$pick_list_key  = $pick_list_arr[0];
				$pick_list_val  = $pick_list_arr[1];
				if($pick_display){
					$pick_list  = "$pick_table.$pick_list_key,CONCAT_WS(\" - \", $pick_table.$pick_display) as $pick_list_val";
				}
				$depen_pick_tbl = $form_result[$dependent_pick]['pick_table'];
				$inner_join 	= ' inner join '.$depen_pick_tbl.' on '.$depen_pick_tbl.'.'.$table_column1.' = '.$pick_table.'.'.$table_column2.'';

				$inner_where 	= ' and '.$depen_pick_tbl.'.trans_status = 1';
				$where_condition 	   = $this->get_role_based_picklist($this->control_name,$prime_form_id);
				$select_qry 	= 'select '.$pick_list.' from '.$pick_table.' '.$inner_join.' where '.$pick_table.'.trans_status = 1 and '.$pick_table.'.'.$table_column2.' = "'.$label_value.'" '.$inner_where.' '.$where_condition.' ';
				$select_info    = $this->db->query("CALL sp_a_run ('SELECT','$select_qry')");
				$select_rslt   	= $select_info->result();
				$select_info->next_result();

				$pick_key 		= array_column($select_rslt, $pick_list_key);
				$pick_value 	= array_column($select_rslt, $pick_list_val);
				$dropdown_list[$label_name]  = array_combine($pick_key ?? [], $pick_value  ?? []);
			}
		}
		echo json_encode(array('success' => TRUE, 'message' => "Proceed..!",'dropdown_list'=>$dropdown_list));
	}
	//DEPENDENT PRIME ID ARRAY FOR ALL DYNAMIC MODULE START
	public function get_depend_fun(){
		$get_depend_arr       = json_decode(json_encode($this->form_info),true);
		$get_depend_prime_id  = array_reduce($get_depend_arr ?? [], function($result, $arr){	
		    $result[$arr['label_name']] = $arr;
		    return $result;
		}, array());
		return $get_depend_prime_id;
	}
	//depend_label_id autopick
	public function depend_label_fun(){
		$get_depend_arr       = json_decode(json_encode($this->form_info),true);
		$depend_label_id  = array_reduce($get_depend_arr ?? [], function($result, $arr){	
			if((int)$arr['field_type'] === 9){
		    	$result[$arr['label_name']] = $arr['dependent_pick_input'];
		    }
		    return $result;
		}, array());
		return $depend_label_id;
	}
	//DEPENDENT PRIME ID ARRAY FOR ALL DYNAMIC MODULE END
	public function suggest_auto_filter(){
		$encString     = file_get_contents('php://input');
		$_POST         = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..'));
			exit(0);
		}
		$search_term    = $this->input->post_get('term');		
		$prime_form_id  = $this->input->post('prime_form_id');
		$form_query     = 'select * from cw_form_setting where prime_form_id = "'.$prime_form_id.'"';
		$form_data   = $this->db->query("CALL sp_a_run ('SELECT','$form_query')");
		$form_result = $form_data->result();
		$form_data->next_result();	
		$where_condition 	   = $this->get_role_based_picklist($prime_form_id,$this->control_name);
		if($form_result){
			$pick_table          = $form_result[0]->pick_table;
			$pick_list           = $form_result[0]->pick_list;
			$auto_prime_id       = $form_result[0]->auto_prime_id;
			$auto_dispaly_value  = $form_result[0]->auto_dispaly_value;
			
			$auto_list = "CONCAT(".str_replace(",",'," - ",',$pick_list).") as auto_list";
			$suggest_query = "select $auto_prime_id,$auto_dispaly_value,$auto_list from $pick_table where ";
			$col_list      = explode(",",$pick_list);
			$where_query  = "";
			foreach($col_list as $col){
				$search_term = str_replace('"',"~",$search_term);
				$search_term = str_replace("'","`",$search_term);
				$where_query .= $col.' like "'.$search_term.'%" or ';
			}
			$where_query    = rtrim($where_query," or ");
			$suggest_query .= $where_query;
			$suggest_query .= $where_condition;
			$suggest_data   = $this->db->query("CALL sp_a_run ('SELECT','$suggest_query')");
			$suggest_result = $suggest_data->result();
			$suggest_data->next_result();
			foreach($suggest_result as $result){
				$suggest_prime_id  = $result->$auto_prime_id;
				$suggest_dispaly   = $result->$auto_dispaly_value;
				$suggest_dispaly   = str_replace("~",'"',$suggest_dispaly);
				$suggest_dispaly   = str_replace("`","'",$suggest_dispaly);
				$suggest_dispaly   = str_replace("^","&",$suggest_dispaly);
				$suggest_list  = $result->auto_list;
				$suggest_list  = str_replace("~",'"',$suggest_list);
				$suggest_list  = str_replace("`","'",$suggest_list);
				$suggest_list  = str_replace("^","&",$suggest_list);
				$suggestions[] = array('value' => $suggest_prime_id, 'label' => $suggest_list, 'display_name' => $suggest_dispaly);
			}
		}
		if(empty($suggestions)){
			$suggestions[] = array('value' => "0", 'label' => "No data found for this search");
		}
		echo json_encode($suggestions);		
	}
	//DHR CODE START FOR TIME SHEET(MI FMS) EXPORT A DATA AND THEN SAME AS USING IMPORT  
	public function get_import_pick_list_qry($pro_pick_list){
		$pro_qry = [];
		foreach($pro_pick_list as $setting){
			$prime_form_id      = (int)$setting->prime_form_id;
			$prime_module_id    = $setting->prime_module_id;
			$input_view_type    = (int)$setting->input_view_type;
			$input_for          = (int)$setting->input_for;
			$field_type         = (int)$setting->field_type;
			$label_id           = $setting->label_name;
			$label_name         = ucwords($setting->view_name);
			$field_length       = $setting->field_length;
			$field_decimals     = $setting->field_decimals;
			$pick_list_type     = (int)$setting->pick_list_type;
			$pick_list          = $setting->pick_list;
			$pick_table         = $setting->pick_table;
			$auto_prime_id      = $setting->auto_prime_id;
			$auto_dispaly_value = $setting->auto_dispaly_value;
			$field_isdefault    = (int)$setting->field_isdefault;
			$file_type          = (int)$setting->file_type;
			$mandatory_field    = (int)$setting->mandatory_field;
			$unique_field       = (int)$setting->unique_field;
			$table_show         = (int)$setting->table_show;
			$search_show        = (int)$setting->search_show;
			$default_value      = (int)$setting->default_value;
			$pick_display       = $setting->pick_display_value;
			$pick_list_import   = (int)$setting->pick_list_import;
			
			if($default_value === 0){
				$default_value = "";
			}
			
			$pick_drop       = array();
			$pick_master     = array();
			$pick_key        = array();
			$pick_val        = array();
			$final_pick      = array();
			$where_condition = "";
			
			//ROLE BASE CONDITION BUILD
			if($this->condition_list[$prime_form_id]){
				$where_condition = $this->condition_list[$prime_form_id];				
				$where_condition = str_replace('^','"',$where_condition);
				foreach($this->session_list as $session_val){
					$session_value 	   = $session_val->session_value;
					$saved_session_val = $this->session->userdata($session_value);
					$exist_val = "@".$session_value."@";
					$where_condition  = str_replace($exist_val,$saved_session_val,$where_condition);
				}
			};

			if($field_isdefault === 1){	 // UDY NEED CHECK
				if(($field_type === 5) || ($field_type === 7)){
					$imp_pick_list_val_1     = '';
					$imp_pick_list_val_2     = '';
					$imp_pick_list_val_3     = '';
					if($pick_list_type === 1){
						$pick_list_val           = explode(",",$pick_list);
						$imp_pick_list_val_1     = $pick_list_val[0];
						$imp_pick_list_val_2     = $pick_list_val[1];
					}else
					if($pick_list_type === 2){
						$imp_pick_list_val_1     = $pick_table."_id";
						$imp_pick_list_val_2     = $pick_table."_value";
						$imp_pick_list_val_3     = $pick_table."_status";
					}
					if($pick_list_import){
						// if($pick_list_import === 1){
							$imp_pick_list = "$imp_pick_list_val_1,CONCAT_WS(\" ~ \", $pick_display) as $imp_pick_list_val_2";
						// }else
						if($pick_list_import === 2){
							$imp_pick_list = "$imp_pick_list_val_2 as $imp_pick_list_val_1,CONCAT_WS(\" ~ \", $pick_display) as $imp_pick_list_val_2";
						}
						$pick_qry    = 'select '.$imp_pick_list.' from '.$pick_table.' where trans_status = 1';
						$pick_qry        = rtrim($pick_qry," ");
						
						$pro_qry[]       = array("return"=>$label_id,"qry"=>$pick_qry,"pro_info"=>array('prime_form_id' => $prime_form_id,'label_id' => $label_id,'label_name' => $label_name,'field_type' => $field_type,'pick_list_type' => $pick_list_type,'imp_pick_list_val_1' => $imp_pick_list_val_1,'imp_pick_list_val_2' => $imp_pick_list_val_2,'table_show' => $table_show,'search_show' => $search_show,'field_isdefault' => $field_isdefault,));
					}
					
				}else
				if($field_type === 9){
					$pick_display_val  = "CONCAT(".str_replace(",",'," ~ ",',$pick_display).") as auto_list_pick";
					$pick_qry          = 'select '.$auto_prime_id.','.$auto_dispaly_value.','.$pick_display_val .' from '. $pick_table .' where trans_status = 1';
					$pick_qry          = rtrim($pick_qry," ");
					$pro_qry[]         = array("return"=>$label_id,"qry"=>$pick_qry,"pro_info"=>array('prime_form_id' => $prime_form_id,'label_id' => $label_id,'label_name' => $label_name,'field_type' => $field_type,'auto_prime_id' => $auto_prime_id,'auto_dispaly_value' => $auto_dispaly_value,'table_show' => $table_show,'search_show' => $search_show,'field_isdefault' => $field_isdefault,));
				}
			}
		}
		
		if(count($pro_qry ?? []) > 0){
			$pick_list_info = $this->run_multi_qry($pro_qry);
			
			if(!$pick_list_info->sts){
				$this->module_sts = false;
			}else{
				$pick_list_rslt = [];
				$pick_list_rslt = json_decode(json_encode($pick_list_info->rslt),true);

				foreach($pick_list_rslt as $pick_key=>$list_info){
					$is_exist_pro_qry = array_search($pick_key, array_column($pro_qry, 'return'));
					if($pro_qry[$is_exist_pro_qry]){
						//pro info array format
						$pro_info         = $pro_qry[$is_exist_pro_qry]["pro_info"];

						$prime_form_id    = $pro_info['prime_form_id'];
						$label_id         = $pro_info['label_id'];
						$label_name       = $pro_info['label_name'];
						$field_type       = (int)$pro_info['field_type'];
						$table_show       = (int)$pro_info['table_show'];
						$search_show      = (int)$pro_info['search_show'];
						$field_isdefault  = (int)$pro_info['field_isdefault'];

						if($field_type === 5 || $field_type === 7){
							$pick_list_type      = (int)$pro_info['pick_list_type'];
							$imp_pick_list_val_1 = $pro_info['imp_pick_list_val_1'];
							$imp_pick_list_val_2 = $pro_info['imp_pick_list_val_2'];
							
							// NEWLY ADDED FOR AVON DB ISSUE _ARN 03-11-2025
							$list_info           = (array)$list_info;
							//CODE START FOR TIME SHEET TABLE DATA EXPORT TO EXCEL (PICKLIST AND AUTO COMPLETE DATA)
							$pick_imp_key        = array_column($list_info, $imp_pick_list_val_2);
							$pick_imp_val        = array_column($list_info, $imp_pick_list_val_1);
							$final_imp_pick      = array_combine( $pick_imp_key ?? [], $pick_imp_val ?? []);
						}else
						if($field_type === 9){
							$auto_prime_id       = $pro_info['auto_prime_id'];
							$auto_dispaly_value  = $pro_info['auto_dispaly_value'];

							// NEWLY ADDED FOR AVON DB ISSUE _ARN 03-11-2025
							$list_info           = (array)$list_info;

							//CODE START FOR TIME SHEET TABLE DATA EXPORT TO EXCEL (PICKLIST AND AUTO COMPLETE DATA)
							$pick_imp_key        = array_column($list_info, 'auto_list_pick');
							$pick_imp_val        = array_column($list_info, $auto_dispaly_value);
							$final_imp_pick      = array_combine( $pick_imp_key ?? [], $pick_imp_val ?? []);
						}
						$this->export_pick_arr[$label_id]   = $final_imp_pick;
					}
				}
			}
		}
	}
	public function picklist_info(){
		if($this->control_name === "employee_log_report"){
			$this->control_name  = "employees";
		}		
		// UDY TEMP NNED TO REMOVE		
		$pro_qry   = [];
		$pro_qry[] = array("return"=>"form_info","qry"=>'select * from cw_form_setting where prime_module_id = "'.$this->control_name.'" and field_show = "1" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",user_right_for) and field_show = 1');
		if(count($pro_qry ?? []) > 0){
			$page_info_rslt         = $this->run_multi_qry($pro_qry);
			$pro_pick_list      = [];
			foreach($page_info_rslt->rslt->form_info as $key => $value){
				$field_type       = (int)$value->field_type;
				$table_show       = (int)$value->table_show;
				$search_show      = (int)$value->search_show;
				$input_view_type  = (int)$value->input_view_type;
				$field_show  	  = (int)$value->field_show;	

				if($field_show === 1){
					if(($field_type === 5) || ($field_type === 7) || ($field_type === 9)){
						$pro_pick_list[$key]  = $value;
					}
				}
			}
			if(count($pro_pick_list ?? []) > 0){
				$this->get_pick_list_qry($pro_pick_list);
			}
		}
	}
	//Resend Mail Dynamic
	public function send_email(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
		$view_id = $this->input->post('view_id');
		if($this->control_name === "offer_letter"){
			$cat_query = 'select category,template from cw_offer_letter where prime_offer_letter_id = "'.$view_id.'" and trans_status = "1"';
			$cat_data     = $this->db->query("CALL sp_a_run ('SELECT','$cat_query')");
			$cat_result = $cat_data->result();
			$cat_data->next_result();
			$category = $cat_result[0]->category;
			$template = $cat_result[0]->template;
			$qry      =  ' and FIND_IN_SET("'.$category.'",print_info_for)';
			//Only for CADD
			$qry      =  ' table_values = "'.$template.'"';
		}else
		if($this->control_name === "employees"){
			$cat_query = 'select role,design_template from cw_employees where prime_employees_id = "'.$view_id.'" and trans_status = "1"';
			$cat_data     = $this->db->query("CALL sp_a_run ('SELECT','$cat_query')");
			$cat_result = $cat_data->result();
			$cat_data->next_result();
			$category = $cat_result[0]->role;
			$template = $cat_result[0]->design_template;
			$qry      =  ' and FIND_IN_SET("'.$category.'",print_info_for)';
			//Only for CADD
			$qry      =  ' table_values = "'.$template.'"';
			//$this->control_name = 'custom_employees';
		}else{
			$qry  ='';
		}
		if($qry && $view_id){
			$mail_send_status = $this->get_dynamic_email_data($view_id,$qry);
		}else{
			$mail_send_status = "";
		}
		
		if($mail_send_status){
			echo json_encode(array('success' => TRUE, 'message' => $mail_send_status));
		}else{
			echo json_encode(array('success' => FALSE, 'message' => "Please try After sometime..."));
		}		
	}
	/* Dynamic mail Start - Latha*/
	public function dynamic_mail_sent($form_id,$pick_array,$previous_data){
		if($this->control_name === "employee_self_portal"){
			$this->control_name  = "employees";
		}
		$arraycompare 	    = array_diff_assoc($pick_array ?? [],$previous_data ?? []);
		$column_data_qry    = 'select cw_email_info.table_values,cw_email_info.query_list_id from cw_email_info where cw_email_info.email_info_module_id = "'.$this->control_name.'" and cw_email_info.process_type = 1 and cw_email_info.trans_status = 1';
		$column_data_info   = $this->db->query("CALL sp_a_run ('SELECT','$column_data_qry')");
		$column_data_rlst	= $column_data_info->result_array();
		$column_data_info->next_result();
		$column_data_rlst   = array_reduce($column_data_rlst, function($result, $arr){
		    $result[$arr['query_list_id']][] = $arr['table_values'];
		    return $result;
		}, array());

		$final_pick 	   = array_intersect_key($arraycompare, $column_data_rlst);
		$column 		   = http_build_query($final_pick, '', '&');
		$column_qry = "";
		$mobile_no = "";
		if($column){
			$column 	   = str_replace('=','" and table_values = "',$column);
			$column 	   = str_replace('&','") or (query_list_id = "',$column);
			$column_qry	   = '(query_list_id = "'.$column.'")';
			$mail_status = "";

			$mail_send_status = $this->get_dynamic_email_data($form_id,$column_qry);
		}else{
			$mail_send_status    = "";
		}
		return $mail_send_status;
			
	}
	//DYNAMIC MAIL SEND PROCESS
	public function get_dynamic_email_data($form_id,$column_qry){
		//Email Info
		$email_info_qry    	= 'select cw_email_info.prime_email_info_id,cw_email_info.email_info_name,cw_email_info.email_attach_column,email_subject,bcc_mail,email_design from cw_email_info INNER JOIN cw_mail_design ON cw_mail_design.email_design_for = cw_email_info.prime_email_info_id where cw_email_info.email_info_module_id = "'.$this->control_name.'" and cw_email_info.process_type = 1 and cw_email_info.trans_status = 1 and '.$column_qry.'';
		$email_data_info   	= $this->db->query("CALL sp_a_run ('SELECT','$email_info_qry')");
		$email_info_rslt	= $email_data_info->result();
		$email_data_info->next_result();
		 //print_r($email_info_rslt);

		$column_data_qry    = 'select email_table_email_column,cw_email_block.prime_email_block_id,email_block_for,email_block_type,email_block_table,email_block_column,email_name_table,email_table_column,email_table_email_column,email_table_list FROM cw_email_block inner join cw_email_info on cw_email_info.prime_email_info_id = cw_email_block.email_block_for INNER JOIN cw_email_table on cw_email_table.email_name_table = cw_email_block.prime_email_block_id WHERE cw_email_block.email_block_module_id = "'.$this->control_name.'" and cw_email_block.trans_status = 1 and cw_email_table.trans_status = 1 and '.$column_qry.' order by cw_email_block.email_block_type';
		//echo $column_data_qry; die;
		$column_data_info   = $this->db->query("CALL sp_a_run ('SELECT','$column_data_qry')");
		$column_data_rsLt   = $column_data_info->result_array();
		$column_data_info->next_result();
		$email_block_rsLt   = array_reduce($column_data_rsLt, function($result, $arr){			
		$result[$arr['email_block_for']][] = $arr;
			return $result;
		}, array());

		 //print_r($email_block_rsLt);die;

		$where_qry    = 'select where_condition,where_for_id from cw_email_table_where where trans_status = 1';
		$where_data   = $this->db->query( "CALL sp_a_run ('SELECT','$where_qry')");
		$where_result = $where_data->result_array();
		$where_data->next_result();
		$where_result = array_reduce($where_result, function($result, $arr){			
			$result[$arr['where_for_id']] = $arr;
			return $result;
		}, array());

		//print_r($where_result);die;

		$table_join_qry  	= 'select line_prime_table,line_prime_col,line_join_type,line_join_table,line_join_col,line_sort,email_table_for_id from cw_email_table_join where trans_status = 1';
		$table_join_info   	= $this->db->query("CALL sp_a_run ('SELECT','$table_join_qry')");
		$table_join_rlst	= $table_join_info->result_array();
		$table_join_info->next_result();
		$table_join_rlst = array_reduce($table_join_rlst, function($result, $arr){			
			$result[$arr['email_table_for_id']][] = $arr;
			return $result;
		}, array());

		$table_content_join_qry  	= 'select line_prime_table_content,line_prime_col_content,line_join_type_content,line_join_table_content,line_join_col_content,line_sort_content,email_content_table_for_id from cw_email_content_table_join where trans_status = 1';
		$table_content_join_info   	= $this->db->query("CALL sp_a_run ('SELECT','$table_content_join_qry')");
		$table_content_join_rslt	= $table_content_join_info->result_array();
		$table_content_join_info->next_result();
		$table_content_join_rslt = array_reduce($table_content_join_rslt, function($result, $arr){			
			$result[$arr['email_content_table_for_id']][] = $arr;
			return $result;
		}, array());

		$form_qry    = 'select prime_module_id,prime_form_id,view_name,label_name,field_type,pick_list_type,pick_list,pick_table,auto_prime_id,auto_dispaly_value from cw_form_setting where trans_status = "1"';
		$form_data   = $this->db->query("CALL sp_a_run ('SELECT','$form_qry')");
		$form_result = $form_data->result_array();
		$form_data->next_result();
		$form_result = array_reduce($form_result, function($result, $arr){			
			$result[$arr['prime_module_id']][$arr['label_name']][] = $arr;
			return $result;
		}, array());

		$session_query      = 'select session_value from cw_session_value where session_for = 1 and trans_status = "1"';
		$session_data       = $this->db->query("CALL sp_a_run ('SELECT','$session_query')");
		$session_result     = $session_data->result();
		$session_data->next_result();

		$config_query  = 'SELECT smtp_server,sender_name,bcc,port_no,sender_email,mail_username,mail_password,connection_type FROM cw_mail_configurations WHERE mail_status = 1 and trans_status = 1';
		$config_info   = $this->db->query("CALL sp_a_run ('SELECT','$config_query')");
		$config_result = $config_info->result();
		$config_info->next_result();

		$attachment_qry  = 'SELECT prime_print_design_id,print_design FROM cw_print_design WHERE trans_status = 1';
		$attachment_info = $this->db->query("CALL sp_a_run ('SELECT','$attachment_qry')");
		$attachment_rlst = $attachment_info->result_array();
		$attachment_info->next_result();
		$attachment_rlst = array_reduce($attachment_rlst, function($result, $arr){			
			$result[$arr['prime_print_design_id']] = $arr;
			return $result;
		}, array());
		
		$get_to_mail = "";
		$cc_mail_column="";
		foreach ($email_info_rslt as $key => $value){
			$prime_email_info_id 	= $value->prime_email_info_id;
			$pdf_name 				= $value->email_info_name;
			$email_subject   		= $value->email_subject;
			$email_design   		= $value->email_design;
			$email_attach_column	= $value->email_attach_column;
			$bcc_mail           	= $value->bcc_mail;
			$attachment 			= $attachment_rlst[$email_attach_column]['print_design'];
			$email_block_rslts      = $email_block_rsLt[$prime_email_info_id];
			foreach ($email_block_rslts as $key => $value){
				$email_block_id 	= $value['prime_email_block_id'];
				$email_block_for 	= $value['email_block_for'];
				$email_block_type 	= $value['email_block_type'];
				$email_block_table 	= $value['email_block_table'];
				$email_block_column = $value['email_block_column'];
				$select_qry_column  = $value['email_table_column'];
				$select_attach_col  = $value['email_table_attach'];
				$email_column       = $value['email_table_email_column'];	
				$email_table_clmn   = 'cw_employees.manager_report';
				$mail_status_name   = $value['email_block_name'];
				// $bcc_mail 			= $value['bcc_mail'];
				
				if((int)$email_block_type === 1){
					$where_prime_id 	 = "cw_".$this->control_name.".prime_".$this->control_name."_id";
					$prime_select_column = $select_qry_column;
				}
				$table_join_result  		= $table_join_rlst[$email_block_id];
				$table_content_join_result  = $table_content_join_rslt[$email_block_id];
				$line_table_query 	        = "";
				foreach ($table_join_result as $join_key => $table){
					$line_prime_table      = $table['line_prime_table'];
					$line_prime_col        = $table['line_prime_col'];
					$line_join_type        = $table['line_join_type'];
					$line_join_table       = $table['line_join_table'];
					$line_join_col         = $table['line_join_col'];
					$line_sort             = $table['line_sort'];
					if((int)$line_sort === 1){
						$line_prime_table  = " $line_prime_table ";
						$line_join_table   = " $line_join_table on $line_join_col = $line_prime_col ";
						$line_table_query .= " $line_prime_table  $line_join_type join $line_join_table"; 
					}else{
						$line_table_query .= " $line_join_type join $line_join_table on $line_join_col = $line_prime_col "; 
					}
				}
				$line_table_content_query 	= "";
				foreach ($table_content_join_result as $join_key => $table){
					$line_prime_table_content      = $table['line_prime_table_content'];
					$line_prime_col_content        = $table['line_prime_col_content'];
					$line_join_type_content        = $table['line_join_type_content'];
					$line_join_table_content       = $table['line_join_table_content'];
					$line_join_col_content         = $table['line_join_col_content'];
					$line_sort_content             = $table['line_sort_content'];
					if((int)$line_sort === 1){
						$line_prime_table_content = " $line_prime_table_content ";
						$line_join_table_content  = " $line_join_table_content on $line_join_col_content = $line_prime_col_content ";
						$line_table_content_query .= " $line_prime_table_content  $line_join_type_content join $line_join_table_content"; 
					}else{
						$line_table_content_query .= " $line_join_type_content join $line_join_table_content on $line_join_col_content = $line_prime_col_content "; 
					}
				}
				if(!$line_table_query){
					$line_table_query = " $email_block_table ";
				}
				if(!$line_table_content_query){
					$line_table_content_query = " $email_block_table ";
				}
				if(!$select_qry_column){
					$select_qry_column = "*";
				}else{
					$select_query 	        = "";
					$pick_query             = "";
					$select_attach_column 	= "";
					$map_column             = explode(",",$select_qry_column);
					foreach($map_column as $table_column){
						$map_column         = explode(".",$table_column);
						$table_name         = $map_column[0];
						$column 	        = $map_column[1];
						$control_name       = str_replace('cw_',"",$table_name);
						$form_result_array  = $form_result[$control_name][$column];
						foreach($form_result_array as $form){
							$prime_form_id      = (int)$form['prime_form_id'];
							$view_name          = $form['view_name'];
							$label_name         = $form['label_name'];
							$field_type         = (int)$form['field_type'];
							$pick_list_type     = (int)$form['pick_list_type'];
							$pick_list          = $form['pick_list'];
							$pick_table         = $form['pick_table'];
							$auto_prime_id      = $form['auto_prime_id'];
							$auto_dispaly_value = $form['auto_dispaly_value'];
							if((int)$field_type === 4){
								$select_query .= 'DATE_FORMAT('.$table_name.'.'.$label_name.', "%d-%m-%Y") as '.$label_name.' , ';
								$select_attach_column .= 'DATE_FORMAT('.$table_name.'.'.$label_name.', "%d-%m-%Y") as '.$label_name.' , ';
							}else
							if(($field_type === 5) || ($field_type === 7)){
								if($pick_list_type === 1){
									$pick_list_val   = explode(",",$pick_list);
									$pick_list_val_1 = $pick_list_val[0];
									$pick_list_val_2 = $pick_list_val[1];

									$pick_query_as = $pick_table."_".$prime_form_id;
									if((int)$email_block_type === 2){
										$email_column = str_replace($pick_table,$pick_query_as,$email_column);
									}
									$select_query         .= "$pick_query_as.$pick_list_val_2 as $label_name,";
									$select_attach_column .= "$pick_query_as.$pick_list_val_2 as $label_name,";
									$pick_query           .= " left join $pick_table as $pick_query_as on $pick_query_as.$pick_list_val_1 = $table_name.$label_name ";									
								}else
								if($pick_list_type === 2){ 
									$pick_list_val_1 = $pick_table."_id";
									$pick_list_val_2 = $pick_table."_value";
									$pick_list_val_3 = $pick_table."_status";
									
									$pick_query_as = $pick_table."_".$prime_form_id;
									$select_query .= "$pick_query_as.$pick_list_val_2 as $label_name,";
									$select_attach_column .= "$pick_query_as.$pick_list_val_2 as $label_name,";
									$pick_query   .= " left join $pick_table as $pick_query_as on $pick_query_as.$pick_list_val_1 = $table_name.$label_name ";
								}
							}else
							if($field_type === 9){
								$pick_query_as = $pick_table."_".$prime_form_id;
								$select_query .= "$pick_query_as.$auto_dispaly_value as $label_name,";
								$select_attach_column .= "$pick_query_as.$auto_dispaly_value as $label_name,";
								$pick_query .= " left join $pick_table as $pick_query_as on $pick_query_as.$auto_prime_id = $table_name.$label_name ";
							}else
							if(($field_type === 2) || ($field_type === 3)){
								$label_ytd     = $label_name."_ytd";
								$select_query .= "$table_name.$label_name,";
								$select_attach_column .= "$table_name.$label_name,";
							}else{
								$select_query .= "$table_name.$label_name,";
								$select_attach_column .= "$table_name.$label_name,";
							}
						}					
					}
				}

				$where_trans      = "";
				$where_trans_info = explode(",",$email_block_table);
				foreach($where_trans_info as $trans_info){
					$where_trans .= "$trans_info.trans_status = 1 and ";
				}
				$where_trans      = rtrim($where_trans,'and ');
				$where_condition  = "";
				if($where_result){
					$where_condition    = str_replace('^','"',$where_result[$email_block_id]['where_condition']);
					$where_condition    = str_replace('@today_date@',date("Y-m-d"),$where_condition);
					$where_condition    = str_replace('@logged_id@',$this->logged_id,$where_condition);				
					$session_date_list  = array("logged_DMY"=>"d-m-Y","logged_YMD"=>"Y-m-d","logged_MY"=>"m-Y","logged_YM"=>"Y-m","logged_Y"=>"Y"); 
					foreach($session_result as $rslt){
						$session_value 	   = $rslt->session_value;
						if($session_value !== "access_data"){
							$exist_val = "@".$session_value."@";
							if($session_date_list[$session_value]){
								$date_formate      = $session_date_list[$session_value];
								$saved_session_val = date($date_formate);
							}else{
								$saved_session_val = $this->session->userdata($session_value);
							}
							$where_condition  = str_replace($exist_val,$saved_session_val,$where_condition);
						}
					}
				}
				
				$select_attach_column = rtrim($select_attach_column,',');
				$email_column = 'CONCAT_WS(",",'.$email_column.') as mail_column';
				if((int)$email_block_type === 1){
					$prime_qry 	  = "select $select_query$select_attach_column from ".$line_table_content_query." $pick_query where $where_prime_id = ".$form_id." and $where_trans $where_condition";
					$prime_data   = $this->db->query("CALL sp_a_run ('SELECT','$prime_qry')");
					$prime_result = $prime_data->result();
					$prime_data->next_result();

					$email_qry 	  = "select $email_column from ".$line_table_query." $pick_query where $where_prime_id = ".$form_id." and $where_trans $where_condition";
					$email_data   = $this->db->query("CALL sp_a_run ('SELECT','$email_qry')");
					$email_result = $email_data->result();
					$email_data->next_result();
					$get_to_mail  = $email_result[0]->mail_column;
				}else{
					$email_qry 	  = "select $email_column from ".$line_table_query." $pick_query where $where_prime_id = ".$form_id." and $where_trans $where_condition";
					$email_data   = $this->db->query("CALL sp_a_run ('SELECT','$email_qry')");
					$email_result = $email_data->result();
					$email_data->next_result();
					$bcc_email        = $email_result[0]->mail_column;
					$cc_mail_column  .= $bcc_email.",";
					$bcc_email_column = rtrim($cc_mail_column,',');
				}				
			}
		}
		// die;
		if($prime_result){
			$assign_date_formate_list  = array("DMY"=>"d-m-Y","YMD"=>"Y-m-d","DFY"=>"d F Y","MY"=>"F-Y","YM"=>"Y-F","D"=>"d","M"=>"M","Y"=>"Y");
			$data['email_sts'] = true;
			foreach($prime_result as $rslt){
				$count++;
				$map_column = explode(",",$prime_select_column);
				$td_line = "";
				foreach($map_column as $table_column){
					$map_column   = explode(".",$table_column);
					$column 	  = $map_column[1];
					$value        = $rslt->$column;
					$replace_val  = "@".$column."@";
					$email_design = str_replace($replace_val,$value,$email_design);
					$attachment   = str_replace($replace_val,$value,$attachment);
					foreach($assign_date_formate_list as $key=>$formate){
						$start         = "@".$key."_";
						$end           = "_".$key."@";
						$replace_val   = $start.$column.$end;
						$replace_val   = $start.$column.$end;
						$date_value    = date_create($value);
						if($date_value){
							$replace_value = date_format($date_value,$formate);
						}						
						$email_design  = str_replace($replace_val,$replace_value,$email_design);
						$attachment  = str_replace($replace_val,$replace_value,$attachment);
					}
				}
			}
		}
		$email_design         = str_replace('~','"',$email_design);
		$attachment           = str_replace('~','"',$attachment);
		$get_attachment 	  = '';
		if($attachment){
			$get_attachment   = $this->get_email_attachment($attachment,$email_subject,$pdf_name);
		}
		if($get_to_mail){
			$mail_send_status = $this->send_mail_dynamic($mail_status_name,$get_to_mail,$config_result,$email_subject,$email_design,$bcc_mail,$get_attachment,$bcc_email_column);
		}else{
			$mail_send_status = "";
		}
		return $mail_send_status;
	}
	public function get_autocomplete_data(){
		//Encryption
		$encString      = file_get_contents('php://input');
		$_POST          = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
		$search_term      = $this->input->post_get('term');		
		$search_qry       = 'select cw_custom_employees.prime_custom_employees_id value,CONCAT(cw_custom_employees.aadhar_card_no," - ",cw_custom_employees.emp_name) as label,cw_custom_employees.aadhar_card_no as display_name from cw_custom_employees where cw_custom_employees.trans_status = 1 and (cw_custom_employees.aadhar_card_no LIKE "%'.$search_term.'%") limit 0,50';
		$search_info      = $this->db->query("CALL sp_a_run ('SELECT','$search_qry')");
		$search_rslt      = $search_info->result_array();
		$search_info->next_result();
		if($search_rslt[0]){ 
			echo json_encode($search_rslt);
		}else{
			echo json_encode(array('success' => false, 'message' => "No Data Found..!"));
		}
	}
	
	//on change unique input validation
	public function input_uniq_validation(){
		//Encryption
		$encString      = file_get_contents('php://input');
		$_POST          = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
		$post_data           = $this->input->post('post_data');		
		$post_json_data      = json_encode($post_data);
		$valid_unique        = $this->db->query("CALL sp_validate_unique ('$post_json_data')");
		$valid_unique_rslt   = $valid_unique->result_array();
		$valid_unique->next_result();
		if($valid_unique_rslt[0]){
			echo json_encode(array('success' => FALSE, 'message' => "Unique Error..!Please View Unique Error Table?","table_info" => $valid_unique_rslt));
			exit(0);
		}else{
			echo json_encode(array('success' => TRUE, 'message' => "Proceed..!"));
		}
	}
	
	//function for validate a unique fields via procedure
	public function unique_procedure_valid($post_json_data){
		$validation_sts_arr  = array();
		//unique procedure call
		$valid_unique        = $this->db->query("CALL sp_validate_unique ('$post_json_data')");
		$valid_unique_rslt   = $valid_unique->result_array();

		$valid_unique->next_result();
		if($valid_unique_rslt[0]){
			$validation_sts_arr = $valid_unique_rslt;
			return $validation_sts_arr;
			// exit(0);
		}else{
			return $validation_sts_arr = array(1);
		}
	}

	//IFSC CODE BASED BANK DETAILS GET
	public function get_bank_details(){
		//Encryption
		$encString      = file_get_contents('php://input');
		$_POST          = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
		$ifsc_code		= $this->input->post("ifsc_code");
		$get_api_data	= $this->get_api_data($ifsc_code);
		$bank_name 		= $get_api_data['BANK'];
		$bank_branch 	= $get_api_data['BRANCH'];
		if($bank_name){
			echo json_encode(array('success'=>TRUE,'message'=>"",'bank_name' => $bank_name,"bank_branch"=>$bank_branch,'get_api_data'=>$get_api_data));
		}else{
			echo json_encode(array('success'=>false,'message'=>"IFSC code Wrong"));
		}
	}
	
	//API BASED ON IFSC CODE 
	public function get_api_data($ifsc_code) {		
		$url   = "https://ifsc.razorpay.com/" . $ifsc_code;
		$ch    = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$json  = curl_exec($ch);
		$error = curl_error($ch);
		curl_close($ch);
		if ($error) {
			echo "cURL Error: " . $error;
			return null;
		}
		$arr = json_decode($json, true);
		if (json_last_error() !== JSON_ERROR_NONE) {
			echo "JSON decoding error: " . json_last_error_msg();
			return null;
		}
		return $arr;
	}

	//TL AND PM FETCH BASED ON TEAM
	public function tl_pm_fetch(){
		//Encryption
		$encString      = file_get_contents('php://input');
		$_POST          = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
		$team           = $this->input->post("team");
		if($this->config->item("db_name") === 'rebar_hrms_db'){
			//TEAM TABLE SELECT QUERY
			$tl_pm_qry      = 'select cw_team.team,cw_team.tl_report,tl.emp_name tl_name,cw_team.manager_report,pm.emp_name pm_name from cw_team inner join cw_employees tl on cw_team.tl_report = tl.employee_code and tl.termination_status = 0 inner join cw_employees pm on cw_team.manager_report = pm.employee_code and pm.termination_status = 0 where cw_team.prime_team_id = "'.$team.'" and tl.trans_status = 1 and pm.trans_status = 1 and cw_team.trans_status = 1';
			$tl_pm_info     = $this->db->query("CALL sp_a_run ('SELECT','$tl_pm_qry')");
			$tl_pm_rslt     = $tl_pm_info->result_array();
			$tl_pm_info->next_result();
			if($tl_pm_rslt){
				echo json_encode(array('success' => true,'message' => 'Proceed.!','tl_pm_arr' => $tl_pm_rslt));
			}else{
				echo json_encode(array('success' => false,'message' => 'Please check TL and PM mapping in Team Master..!','tl_pm_arr' => $tl_pm_rslt));
			}
		}else{
			echo json_encode(array('success' => true,'message' => 'Proceed.!','tl_pm_arr' => array()));
		}
	}
	
	public function time_diff_calculate(){
		//Encryption
		$encString      = file_get_contents('php://input');
		$_POST          = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
		$permission_date  = date("Y-m-d",strtotime($this->input->post('permission_date')));
		$in_time          = $this->input->post('in_time');
		$out_time         = $this->input->post('out_time');
		//CONVERT STRING TO DATE FORMAT
		$in_time          = new DateTime($in_time);
   		$out_time         = new DateTime($out_time);
   		$timeDiff         = $in_time->diff($out_time);
   		$total_time       = $timeDiff->format("%H:%I:%S");

		if($total_time){
			echo json_encode(array('success' => TRUE, 'total_time' => $total_time));
		}else{
			echo json_encode(array('success' => FALSE,));
		}
	}

	//FUNCTION FOR MANUAL PUNCH
	public function diff_date_time_cal(){
		//Encryption
		$encString      = file_get_contents('php://input');
		$_POST          = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
		$text            = $this->input->post('text');
		$in_date         = date("Y-m-d",strtotime($this->input->post('in_date')));
		$out_date        = date("Y-m-d",strtotime($this->input->post('out_date')));
		$in_time         = $this->input->post('in_time');
		$out_time        = $this->input->post('out_time');
		$in_time_count   = count(explode(":",$in_time));
		$out_time_count  = count(explode(":",$out_time));
		$total_time      = $this->total_time_cal($in_date,$out_date,$in_time,$out_time,$in_time_count,$out_time_count);
		if($total_time){
			echo json_encode(array('success' => TRUE, 'total_time' => $total_time));
		}else{
			echo json_encode(array('success' => FALSE));
		}
	}

	//function for only reber time office 
	public function change_shift_validate(){
		//Encryption
		$encString     = file_get_contents('php://input');
		$_POST         = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
		$employee_code        = $this->input->post('employee_code');
		$shift_date           = date("Y-m-d",strtotime($this->input->post('shift_date')));
		$current_shift        = $this->input->post('current_shift');
		$change_shift         = (int)$this->input->post('change_shift');
		//FINANCIAL YEAR DETAILS
		$financial_info       = $this->get_leave_financial_details();
		$financial_year_id    = $financial_info[0]->prime_leave_financial_year_id;

		//EMP DETAILS QRY
		$emp_details_query    = 'SELECT role as category,gender,grade from cw_employees WHERE employee_code = "'. $employee_code .'" and trans_status = 1';
		$emp_details_info     = $this->db->query("CALL sp_a_run ('SELECT','$emp_details_query')");
		$emp_details_result   = $emp_details_info->result();
		$emp_details_info->next_result();	

		$category             = $emp_details_result[0]->category;
		$gender               = $emp_details_result[0]->gender;
		$grade                = $emp_details_result[0]->grade;

		$shift_eligible_qry   = 'SELECT cw_shift_eligibility.to_shift FROM cw_shift_eligibility WHERE FIND_IN_SET("'.$category.'",cw_shift_eligibility.category) and FIND_IN_SET("'.$gender.'",cw_shift_eligibility.gender) and FIND_IN_SET("'.$grade.'",cw_shift_eligibility.grade) and cw_shift_eligibility.from_shift = "'.$current_shift.'" and cw_shift_eligibility.trans_status = 1';
		// count(prime_shift_eligibility_id) as count
		// cw_shift_eligibility.category = "'.$category.'" and cw_shift_eligibility.gender = "'.$gender.'" and cw_shift_eligibility.grade = "'.$grade.'" and
		// and cw_shift_eligibility.to_shift = "'.$change_shift.'"
		$shift_eligible_info  = $this->db->query("CALL sp_a_run ('SELECT','$shift_eligible_qry')");
		$shift_eligible_rslt  = $shift_eligible_info->result_array();
		$shift_eligible_info->next_result();	
		if(!count($shift_eligible_rslt ?? [])){
			echo json_encode(array('success' => TRUE));
		}else{
			$change_shift_arr     = array_column($shift_eligible_rslt,"to_shift");
			if(!in_array($change_shift, $change_shift_arr)){
				echo json_encode(array('success' => FALSE, 'message' => "Could not Change this Shift. Please Check Shift Eligibility..?"));
			}else{
				echo json_encode(array('success' => TRUE));
			}
		}
	} 

	//DR TESTING FOR SAMPLE CSV FORMAT USING TO IMPORT
	public function do_csv_emp_import($import_id){
		$filename = dirname(__FILE__)."/php_excel/PHPExcel/IOFactory.php";
		include($filename);
		if($import_id < 0){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}		
		$excel_path_qry    = 'select * from cw_import where import_id = "'.$import_id.'"';
		$excel_path_info   = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
		$excel_path_result = $excel_path_info->result();
		$excel_path_info->next_result();
		if(!$excel_path_result){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}else{
			$excel_file_path    = $excel_path_result[0]->excel_file_path;
			$module_id          = $excel_path_result[0]->module_id;
			$import_type        = $excel_path_result[0]->import_type;
			$excel_format       = $excel_path_result[0]->excel_format;
			$excel_sheet_name   = (int)$excel_path_result[0]->excel_sheet_name;
			$excel_row_start    = (int)$excel_path_result[0]->excel_start_row;
			$excel_row_end      = (int)$excel_path_result[0]->excel_end_row;
			//SELECT EXCEL FORMAT AND FORMAT LINE DATA GET	
			$format_qry 	= 'select cw_util_excel_format.*,excel_line_column_name,excel_line_value from cw_util_excel_format inner join cw_util_excel_format_line on (cw_util_excel_format_line.prime_excel_format_id = cw_util_excel_format.prime_excel_format_id and cw_util_excel_format_line.prime_excel_format_id = "'.$excel_format.'") where cw_util_excel_format.prime_excel_format_id = "'.$excel_format.'" and cw_util_excel_format.trans_status = 1 and cw_util_excel_format_line.trans_status = 1 ORDER BY excel_line_value ASC';
			$format_info    = $this->db->query("CALL sp_a_run ('SELECT','$format_qry')");
			$format_rslt    = $format_info->result_array();
			$format_info->next_result();

			// print_r($format_rslt);die;
			if(empty($format_rslt)){
				return json_encode(array('success' => false, 'message' => "Please add excel format before import"));
			}else{
				$head_col_arr  = array_column($format_rslt,"excel_line_value","excel_line_column_name");
				$head_name_arr = array_column($format_rslt,"excel_line_column_name","excel_line_column_name");
				if($excel_file_path){
					$excel_array        = array();
					if(($open = fopen($excel_file_path, "r")) !== FALSE){
						// $i    = 1;
						//LOOPING A DATA FROM CSV FILE
						while (($data = fgetcsv($open)) !== FALSE){        
							// $excel_array[$i] = $data; 
							$excel_array[] = $data; 
							// $i++;
						}
						fclose($open);
					}
					if(!empty($excel_array)){
						// $excel_head_arr   = $excel_array[1];
						// $excel_head_arr   = $excel_array[0];
						// $excel_data_arr   = array_slice($excel_array, 1, -1, true);
						$excel_data_arr   = array_slice($excel_array, 1);
					}
					
					// print_r($excel_head_arr);
					// print_r($excel_data_arr);
					// die;
				}
			}
		}
	}
	// COFF LATE CHECKING
	public function check_coff_late($employee_code,$from_date){
		//Get Category from employees
		$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;
		$get_coff_result  = $this->get_coff_settings($employee_code,$emp_category);

		$halfday_min      = $get_coff_result[0]->halfday_min;
		$ot_activated     = $get_coff_result[0]->ot_activated;
		$halfday_hours    = $this->hours_mins_cal($halfday_min);
		$coff_late_date   =  date("Y-m-d",strtotime("-1 day",strtotime($from_date)));
		$perm_entry_qry   = 'select count(prime_permission_entry_id) as count from cw_permission_entry where trans_status = 1 and employee_code = "'.$employee_code.'" and permission_date = "'.$from_date.'"';
		$perm_info        = $this->db->query("CALL sp_a_run ('RUN','$perm_entry_qry')");
		$perm_result      = $perm_info->result();
		$perm_info->next_result();
		$perm_count       = (int)$perm_entry_result[0]->count;
		if($perm_count > 0){
			echo json_encode(array('success' => FALSE, 'message' => "Already Coff Late Permission Taken"));
			exit(0);
		}
		$time_entry_qry    = 'select coff_hours,employee_code,att_date from cw_time_entry where trans_status = 1 and cw_time_entry.employee_code = "'.$employee_code.'" and att_date = "'.$coff_late_date.'"';
		$time_entry_info   = $this->db->query("CALL sp_a_run ('RUN','$time_entry_qry')");
		$time_entry_result = $time_entry_info->result_array();
		$time_entry_info->next_result();
		$coff_hours        = $time_entry_result[0]['coff_hours'];
		if((int)$halfday_min < (int)$coff_hours){
			echo json_encode(array('success' => FALSE, 'message' => "Coff Late Hours should be greater than or equal to $halfday_hours"));
						exit(0);
		}else{
			return true;
		}
	}
	public function coff_update($employee_code,$prime_financial_id,$created_on,$category,$app_over_time,$approval_status,$entry_date,$form_id){
		$app_over_time_mins = $this->hourstomins($app_over_time);

		$leave_creation_qry    = 'SELECT leave_name from cw_leave_creation where cw_leave_creation.trans_status = 1 and coff = 1 and leave_opening = 1';
		$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_name  		   = strtolower($leave_creation_result[0]->leave_name);

		//Check Half day hours and Fullday Hours
		$company_info       = $this->company_info();
		$coff_based_on      = $company_info[0]->coff_based_on; //Get from company info module.
		$coff_check_qry = "";
		if($coff_based_on !== 'role' && $coff_based_on !== '0'){
			$coff_check_val = $this->emp_pick_arr[$employee_code][$coff_based_on];
			$coff_check_qry = ' and FIND_IN_SET('.$coff_check_val.', cw_coff_settings.check_input)';
		}
		$check_inp_qry     = 'SELECT halfday_min,fullday_min,expiry_days,max_ot_hours,credit_apply_before,expire_salary_date from cw_coff_settings where FIND_IN_SET('.$category.', cw_coff_settings.category) '.$coff_check_qry;
		$check_inp_info    = $this->db->query("CALL sp_a_run ('SELECT','$check_inp_qry')");
		$check_inp_result  = $check_inp_info->result();
		$check_inp_info->next_result();
		$halfday_min       = $check_inp_result[0]->halfday_min;
		$fullday_min       = $check_inp_result[0]->fullday_min;
		$expiry_day        = $check_inp_result[0]->expiry_days;
		$max_ot_hours      = $check_inp_result[0]->max_ot_hours;
		$apply_before      = $check_inp_result[0]->credit_apply_before;
		$exp_salary_date   = $check_inp_result[0]->expire_salary_date;
		//collect credit and expiry dates
		if($apply_before){
			$credited_date = date("Y-m-d",strtotime($entry_date. " - $apply_before days"));
		}else{
			$credited_date = date("Y-m-d",strtotime($entry_date));
		}
		$expiry_date       = date("Y-m-d",strtotime($credited_date. " + $expiry_day days"));
		$salary_end_date   = $expiry_date;
		if($exp_salary_date){
			$month_day_result  = $this->tos_day_qry_fun(1); //get leave month days
			if($month_day_result){
				$day_conditions     = (int)$month_day_result[0]->day_conditions;
				$day_count          = $month_day_result[0]->day_count;
				if((int)$day_conditions === 1){
					$salary_end_date   = date("Y-m-$day_count",strtotime($entry_date));
				}else
				if((int)$day_conditions === 2){
					//GET LAST DATE FOR CUTTOFF TYPE ONLY
					$salary_end_date   = date("Y-m-t",strtotime($entry_date));
				}else
				if((int)$day_conditions === 3){
					//GET LAST DATE FOR CUTTOFF TYPE ONLY
					$day_start       = $month_day_result[0]->day_start;
					$day_end         = $month_day_result[0]->day_end;	
					$entry_date      = date("d",strtotime($entry_date));
					if($entry_date > $day_end){
						$salary_end_date =  date("Y-m-$day_end",strtotime($entry_date. " - 1 month"));
					}else{
						$salary_end_date =  date("Y-m-$day_end",strtotime($entry_date));
					}					
				}
				if($expiry_date < $salary_end_date){ //If expaired before salary end date
					$expiry_date = $salary_end_date;
				}
			}
		}

		if($app_over_time_mins >= $halfday_min && $app_over_time_mins < $fullday_min){ //Half day cond
			$coff_days = 0.5;
		}else
		if($app_over_time_mins >= $fullday_min){
			//worked for coff more than 1 day credited functionality

			/*$full_day  = FLOOR($app_over_time_mins/$fullday_min);
			$diff      = $app_over_time_mins % $fullday_min;
			$half_day  = FLOOR($diff/$halfday_min);
			if($half_day == '1'){
				$half_day = 0.5;
			}else{
				$half_day = 0;
			}
			$coff_days = $full_day + $half_day; */
			$coff_days = 1;
		}
		if((int)$approval_status === 2){
			$update_qry = " $leave_name = $leave_name+$coff_days ";
		}else{
			$update_qry = " $leave_name = $leave_name-$coff_days ";
		}

		$upd_coff_entry_qry   = 'UPDATE cw_leave_opening SET '.$update_qry.',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 trans_status = 1';
		$upd_coff_entry_info  = $this->db->query("CALL sp_a_run ('RUN','$upd_coff_entry_qry')");
		if($upd_coff_entry_info){
			if((int)$approval_status === 2){
				$coff_ins_qry  = 'INSERT into cw_coff_entry(category,employee_code,credited_date,end_date,coff_mins,coff_count,balance_count,ot_hours,max_ot_hours,coff_hours,halfday_min,fullday_min,financial_setting_id,approved_id,trans_created_by,trans_created_date) values ("'.$category.'","'.$employee_code.'","'.$credited_date.'","'.$expiry_date.'","'.$app_over_time_mins.'","'.$coff_days.'","'.$coff_days.'","'.$app_over_time.'","'.$max_ot_hours.'","'.$app_over_time.'","'.$halfday_min.'","'.$fullday_min.'","'.$prime_financial_id.'","'.$form_id.'","'.$this->logged_id.'","'.$created_on.'")';
				$upd_coff_entry_info = $this->db->query("CALL sp_a_run ('RUN','$coff_ins_qry')");
			}else
			if((int)$approval_status === 4){
				$upd_coff_entry_qry   = 'UPDATE cw_coff_entry SET coff_status = "4",trans_updated_by = "'.$this->logged_id.'",trans_updated_date = "'.$created_on.'" WHERE cw_coff_entry.employee_code = "'.$employee_code.'" and cw_coff_entry.financial_setting_id = "'.$prime_financial_id.'" and trans_status = 1';
				$upd_coff_entry_info  = $this->db->query("CALL sp_a_run ('RUN','$upd_coff_entry_qry')");
			}
			if($upd_coff_entry_info){
				return true;
			}
		}
	}
	
	//TIME ENTRY COFF HOURS GET
	public function time_entry_coff_hrs($prime_financial_id,$employee_code,$coff_permission_date){
		$time_entry_qry      = 'select coff_hours from cw_time_entry where cw_time_entry.employee_code = "'.$employee_code.'" and cw_time_entry.att_date = "'.$coff_permission_date.'" and cw_time_entry.trans_status = 1';
		$time_entry_info     = $this->db->query("CALL sp_a_run ('SELECT','$time_entry_qry')");
		$time_entry_rslt     = $time_entry_info->result_array();
		$time_entry_info->next_result();

		return $time_entry_rslt;
	}
	
	// TIMI LOG IN TIME GET
	public function time_log_in_time($prime_financial_id,$employee_code,$log_date,$device_code){
		$time_log_date_qry    = 'select MIN(cw_time_log.log_date) as min_log_date from cw_time_log where cw_time_log.user_id = "'.$device_code.'" and DATE(cw_time_log.log_date) = "'.$log_date.'" and cw_time_log.trans_status = 1';
		// 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_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();

		return $time_log_date_rslt;
	}
	
	//FUNCTION FOR GET SHIFT NAME FOR LEAVE REQUEST DATE
	public function shift_date_validate($employee_code,$from_date,$to_date){
		$from_to_date_arr = array();
		//CHECK FROM DATE AND TO DATE WAS ONE DATE DIFFERENCE
		$check_diff_date  = date("Y-m-d",strtotime("+1 days",strtotime($from_date)));
		//MORE THAN ONE DAY DIFFERENCE
		if($from_date !== $to_date && $to_date !== $check_diff_date){
			$period = new DatePeriod(
				new DateTime("$from_date"),
				new DateInterval('P1D'),
				new DateTime(date("Y-m-d",strtotime("+1 days",strtotime($to_date))))
			);
			foreach($period as $key => $value) {
				$db_date         = $value->format('Y-m-d');
				$show_date       = $value->format('d-m-Y');	
				$from_to_date_arr[$db_date]   = $db_date;
			}
		}else{//FROM AND TO DATE BETWEEN ONE DAY DIFFERENCE
			$from_to_date_arr[$from_date]  = $from_date;
			if($from_date !== $to_date){
				$from_to_date_arr[$to_date]  = $to_date;
			}
		}
		$from_to_date_count      = count($from_to_date_arr ?? []);		
		//GET SHIFT DATES FROM SHIFT MASTER
		$shift_import_qry     = 'select cw_shift_import.prime_shift_import_id,cw_shift_import.shift_date from cw_shift_import where cw_shift_import.employee_code = "'.$employee_code.'" and cw_shift_import.shift_date >= "'.$from_date.'" and cw_shift_import.shift_date <= "'.$to_date.'" 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_array();
		$shift_import_info->next_result();
		
		$shift_import_arr     = array_map(function($value){
			$return_array     = array();
			$return_array['shift_date'] = $value['shift_date'];
			return $return_array;
		}, $shift_import_rslt);
		$shift_date_arr       = array_column($shift_import_arr,"shift_date","shift_date");

		$shift_date_count     = count($shift_date_arr ?? []);

		if((int)$from_to_date_count !== (int)$shift_date_count){
			echo json_encode(array('success' => FALSE, 'message' => "Shift not added to Your Leave Date.? Please Contact Admin.!"));
			exit(0);
		}else{
			return true;
		}
	}

	//FUNCTION FOR GET SHIFT NAME FOR LEAVE AND OT REQUEST DATE
	public function other_request_exist($employee_code,$financial_year_id,$from_date,$to_date,$from_date_type,$to_date_type){
		$between_date_from   = '';
		$between_date_to     = '';
		//------------- FULL DAY TYPE BASED DATE ONLY EXIST COUNT CHECK ----------------
		//CHECK FROM DATE AND TO DATE WAS ONE DATE DIFFERENCE
		$check_diff_date  = date("Y-m-d",strtotime("+1 days",strtotime($from_date)));
		//MORE THAN ONE DAY DIFFERENCE
		if($from_date !== $to_date && $to_date !== $check_diff_date){
			// FULL DAY TYPE ONLY EXIST CHECK
			if($from_date_type === 1){
				$between_date_from  = $from_date;
			}else{
				$between_date_from  = $check_diff_date;
			}
			// FULL DAY TYPE ONLY EXIST CHECK
			if($to_date_type === 1){
				$between_date_to  = $to_date;
			}else{
				$between_date_to  = date("Y-m-d",strtotime("-1 days",strtotime($to_date)));
			}
		}else{
			//FOR FULL DAY TYPE ONLY CHECK
			if($from_date_type === 1){
				$between_date_from    = $from_date;
			}
			if($from_date !== $to_date){
				//FOR FULL DAY TYPE ONLY CHECK
				if($to_date_type === 1){
					$between_date_to  = $to_date;
				}
			}
		}
		//FROM AND TO DATE WHERE COND BUILD
		$date_where_cond       = '';
		if($between_date_from && $between_date_to){
			$date_where_cond   = ' and cw_permission_entry.permission_date >= "'.$between_date_from.'" and cw_permission_entry.permission_date <= "'.$between_date_to.'"';
		}else
		if($between_date_from){
			$date_where_cond   = ' and cw_permission_entry.permission_date = "'.$between_date_from.'"';
		}else
		if($between_date_to){
			$date_where_cond   = ' and cw_permission_entry.permission_date = "'.$between_date_to.'"';
		}
		if(!$date_where_cond){
			return true;
		}else{
			//check exist from permission entry 
			$permission_entry_qry  = 'SELECT count(cw_permission_entry.prime_permission_entry_id) as count FROM cw_permission_entry WHERE cw_permission_entry.employee_code = "'.$employee_code.'"'.$date_where_cond.' and cw_permission_entry.leave_status in (1,2) and financial_setting_id = "'.$financial_year_id.'" and trans_status = 1';
			$permission_entry_info = $this->db->query("CALL sp_a_run ('SELECT','$permission_entry_qry')");
			$permission_entry_rslt = $permission_entry_info->result();
			$permission_entry_info->next_result();	
			$permission_count      = (int)$permission_entry_rslt[0]->count;

			if($permission_count){
				echo json_encode(array('success' => FALSE, 'message' => "Already Permission Request Exist.!"));
				exit(0);
			}else{
				return true;
			}
		}
	}

	//FUNCTION FOR PERMISSION DATE CHECK EXIST FROM LEAVE AND OD ENTRY
	public function check_exist_leave_od($component_value,$financial_year_id,$employee_code,$check_date){
		//CHECK EXIST FROM LEAVE ENTRY [PNLY FOR FULL DAY TYPE] 
		$leave_entry_qry  = 'SELECT count(cw_leave_entry.prime_leave_entry_id) as count FROM cw_leave_entry WHERE cw_leave_entry.employee_code = "'.$employee_code.'" and cw_leave_entry.leave_date = "'.$check_date.'" and cw_leave_entry.leave_status in (1,2) and cw_leave_entry.date_type in (1) and cw_leave_entry.financial_setting_id = "'.$financial_year_id.'" and cw_leave_entry.trans_status = 1';
		$leave_entry_info = $this->db->query("CALL sp_a_run ('SELECT','$leave_entry_qry')");
		$leave_entry_rslt = $leave_entry_info->result();
		$leave_entry_info->next_result();	
		$leave_count      = (int)$leave_entry_rslt[0]->count;

		if($leave_count){#comment will remove confirm it -ARN 07-03-2026
			// echo json_encode(array('success' => false, 'message' => "Already Leave Request Exist.! Please Cancel the Previous Transaction and try Again.!"));
			// exit(0);
			return false;
		}else{
			//CHECK EXIST FROM OD ENTRY [ONLY FOR FULL DAY TYPE] 
			$od_entry_qry  = 'SELECT count(cw_on_duty_entry.prime_on_duty_entry_id) as count FROM cw_on_duty_entry WHERE cw_on_duty_entry.employee_code = "'.$employee_code.'" and cw_on_duty_entry.on_duty_date = "'.$check_date.'" and cw_on_duty_entry.financial_setting_id = "'.$financial_year_id.'" and cw_on_duty_entry.on_duty_status in (1,2) and cw_on_duty_entry.date_type in (1) and cw_on_duty_entry.trans_status = 1';
			$od_entry_info = $this->db->query("CALL sp_a_run ('SELECT','$od_entry_qry')");
			$od_entry_rslt = $od_entry_info->result();
			$od_entry_info->next_result();	
			$od_count      = (int)$od_entry_rslt[0]->count;
			if($od_count){#comment will remove confirm it -ARN 07-03-2026
				// echo json_encode(array('success' => false, 'message' => "Already OD Request Exist.! Please Cancel the Previous Transaction and try Again.!"));
				// exit(0);
				return false;
			}else{
				return true;
			}
		}
	}
	
	//FOR REQUEST AND DIRECT LEAVE ENTRY	
	public function get_emp_details(){
		$encString     = file_get_contents('php://input');
		$_POST         = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
		$employee_code 		= $this->input->post("employee_code");
		$request_type 		= $this->input->post("request_type");
		$request_details    = "";
		if($employee_code){
			if((int)$request_type === 1){
				$request_details      = $this->view_leave_details($employee_code);
			}else
			if((int)$request_type === 4){
				$request_details      = $this->view_permission_details($employee_code);
			}
			echo json_encode(array('success' => 'success', 'request_details' => $request_details));
		}else{
			echo json_encode(array('success' => false));
		}
	}

	//FOR REQUEST AND DIRECT LEAVE ENTRY
	public function view_leave_details($emp_code){
		$financial_info         = $this->get_leave_financial_details();
		$leave_fin_year_id      = $financial_info[0]->prime_leave_financial_year_id;
		$leave_qry 				= 'select cw_leave_opening.*,cw_employees.emp_name from cw_leave_opening inner join cw_employees on cw_employees.employee_code = cw_leave_opening.employee_code where cw_leave_opening.employee_code = "'.$emp_code.'" and cw_leave_opening.trans_status = 1 and financial_setting_id = "'.$leave_fin_year_id.'"';
		$leave_info       		= $this->db->query($leave_qry);
		$leave_result  			= $leave_info->result();
		$leave_info->next_result();
		$emp_name 				= $leave_result[0]->emp_name; 

		$leave_creation_qry 	= 'select cw_leave_creation.leave_description,cw_leave_creation.leave_name from cw_leave_creation where cw_leave_creation.trans_status = 1 and leave_opening = 1';
		$leave_creation_info    = $this->db->query($leave_creation_qry);
		$leave_creation_result  = $leave_creation_info->result();
		$leave_creation_info->next_result();
		$table_list             = "";		
		$rowspan_count 	   	    = count($leave_creation_result ?? []);

		foreach ($leave_creation_result as $key => $value) {
		  	if($key === 0){
		  		$rowspan_collumn = "<td rowspan=$rowspan_count>".$emp_code."</td>
		    	<td rowspan=$rowspan_count>".$emp_name."</td>";
		  	}else{
		  		$rowspan_collumn = "";
		  	}
		  	foreach ($leave_result as $key => $leave_value) {
			  	$leave_name 		= $value->leave_name;
			  	$leave_name_small 	= strtolower($value->leave_name);
			  	$leave_credit 		= $leave_name_small."_credit";
			  	$leave_debit 		= $leave_name_small."_debit";
			  	$leave_used 		= "used_".$leave_name_small;
			  	$leave_pending 		= "pending_".$leave_name_small;
				$leave_encash       = "encash_".$leave_name_small;
			  	$leave_credit 		= $leave_value->$leave_credit;
			  	$opening 			= $leave_value->$leave_name_small;
			  	$credit_plus 		= $leave_credit + $opening;
			  	$leave_debit 		= $leave_value->$leave_debit;
			  	$leave_used 		= $leave_value->$leave_used;
			  	$leave_pending 		= $leave_value->$leave_pending;
			  	$leave_encash 		= $leave_value->$leave_encash;


			  	$balance_value 		= $credit_plus - $leave_debit;
			  	$balance_value 		= $balance_value-$leave_used;
			  	$balance_value 		= $balance_value-$leave_encash;
			  	$balance_value 		= $balance_value-$leave_pending;
			  	$balance_value = number_format($balance_value, 2); 
				$table_list .= "<tr>
			    ".$rowspan_collumn."
			    <td>".$value->leave_description."</td>
			    <td>".$leave_value->$leave_name_small."</td>
			    <td>".$leave_credit."</td>
			    <td>".$leave_debit."</td>
			    <td>".$leave_used."</td>
				<td>".$leave_encash."</td>
			    <td>".$leave_pending."</td>
			    <td><b style='color:green'>".$balance_value."</b></td>
			  </tr>";
			}
		}
		return $table_list;
	}

	public function get_emp_request_data($employee_code){
		$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 = 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;
		$col_name            = $component_result[0]->label_name;
		$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];
	
		$emp_details_qry      ='SELECT  CONCAT(cw_employees.employee_code,"-",cw_employees.emp_name) AS employee_code,cw_employees.date_of_joining,cw_employees.first_level_approval,'.$pick_table.'.'.$pick_list_val_2.' AS component_value,cw_employees.second_level_approval,cw_approval_type.approval_type AS approve_type,cw_employees.device_code,cw_department.department AS department FROM cw_employees INNER JOIN cw_department ON cw_department.prime_department_id = cw_employees.department INNER JOIN cw_approval_type ON cw_approval_type.prime_approval_type_id = cw_employees.approve_type inner join  '.$pick_table.' on  '.$pick_table.'.'.$pick_list_val_1.' =  cw_employees.'.$col_name.' WHERE cw_employees.employee_code = "'.$employee_code.'" AND cw_employees.trans_status = 1 GROUP BY cw_employees.employee_code';
		$emp_data             = $this->db->query("CALL sp_a_run ('SELECT','$emp_details_qry')");
		$emp_result           = $emp_data->result();
		$emp_data->next_result();
		$first_level_approval = $emp_result[0]->first_level_approval;
		$hr_approval          = $emp_result[0]->second_level_approval;
		$approval_manager_qry ='SELECT DISTINCT(SELECT CONCAT(employee_code,"-",emp_name) FROM cw_employees WHERE employee_code="'.$first_level_approval.'")AS first_level,(SELECT CONCAT(employee_code,"-",emp_name) FROM cw_employees WHERE employee_code="'.$hr_approval.'")AS hr_approval FROM cw_employees GROUP BY employee_code,prime_employees_id'; 
		$appr_manager_data    = $this->db->query("CALL sp_a_run ('SELECT','$approval_manager_qry')");
		$approve_manager_rslt = $appr_manager_data->result();
		$appr_manager_data->next_result();

		$first_approve      = $approve_manager_rslt[0]->first_level;
		$hr_approval        = $approve_manager_rslt[0]->hr_approval;
		$emp_code             = $emp_result[0]->employee_code;
		if($emp_result[0]->date_of_joining){
			$doj              = date('d-m-Y',strtotime($emp_result[0]->date_of_joining));
		}else{
			$doj              = "-";
		}
		$department           = $emp_result[0]->department;
		$component_value            = $emp_result[0]->component_value;
		$approve_type         = $emp_result[0]->approve_type;
		$emp_list_data   ="<tr>
		<td style='text-align:center'>".$emp_code."</td>
		<td style='text-align:center'>".$component_value."</td>
		<td style='text-align:center'>".$doj."</td>
		<td style='text-align:center'>".$department."</td>
		<td style='text-align:center'>".$approve_type."</td>
		<td style='text-align:center'>".$first_approve."</td>
		<td style='text-align:center'>".$hr_approval."</td>
	  </tr>";
		  return $emp_list_data;

	}
	//Get Approval employee data
	public function get_emp_approval_data($view_id){
		$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 = 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;
		$col_name            = $component_result[0]->label_name;
		$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];
	
		$emp_details_qry     = 'SELECT  CONCAT(cw_employees.employee_code,"-",cw_employees.emp_name) AS employee_code,CONCAT(level1.employee_code,"-",level1.emp_name)AS first_level_approval,CONCAT(level2.employee_code,"-",level2.emp_name) AS second_level_approval,cw_employees.date_of_joining,'.$pick_table.'.'.$pick_list_val_2.' AS component_value,cw_approval_type.approval_type AS approve_type,cw_employees.device_code,cw_department.department AS department,cw_approval_leave_status.approval_leave_status,status1.approval_leave_status as level1,status2.approval_leave_status as level2,applied_on FROM cw_approval inner join cw_employees on cw_employees.employee_code = cw_approval.employee_code inner join cw_employees as level1 on  level1.employee_code = cw_approval.first_level_approval LEFT join cw_employees as level2 on  level2.employee_code = cw_approval.second_level_approval INNER JOIN cw_department ON cw_department.prime_department_id = cw_employees.department INNER JOIN cw_approval_type ON cw_approval_type.prime_approval_type_id = cw_employees.approve_type INNER JOIN cw_approval_leave_status as status1 ON status1.prime_approval_leave_status_id = cw_approval.first_approval_leave_status INNER JOIN cw_approval_leave_status as status2 ON status2.prime_approval_leave_status_id = cw_approval.second_approval_leave_status INNER JOIN cw_approval_leave_status ON cw_approval_leave_status.prime_approval_leave_status_id = cw_approval.leave_status inner join  '.$pick_table.' on  '.$pick_table.'.'.$pick_list_val_1.' =  cw_employees.'.$col_name.' WHERE cw_approval.prime_approval_id = "'.$view_id.'" AND cw_employees.trans_status = 1 GROUP BY cw_employees.employee_code';
		$emp_data             = $this->db->query("CALL sp_a_run ('SELECT','$emp_details_qry')");
		$emp_result           = $emp_data->result();
		$emp_data->next_result();
		$first_level_approval = $emp_result[0]->first_level_approval;
		$hr_approval          = $emp_result[0]->second_level_approval;		
		$emp_code             = $emp_result[0]->employee_code;
		if($emp_result[0]->date_of_joining){
			$doj              = date('d-m-Y',strtotime($emp_result[0]->date_of_joining));
		}else{
			$doj              = "-";
		}
		$department           = $emp_result[0]->department;
		$component_value      = $emp_result[0]->component_value;
		$approve_type         = $emp_result[0]->approve_type;
		$level1               = $emp_result[0]->level1;
		$level2               = $emp_result[0]->level2;
		$leave_status         = $emp_result[0]->approval_leave_status;
		$applied_on           = date("d-m-Y",strtotime($emp_result[0]->applied_on));
		$emp_list_data   	  = "<tr>
								<td style='text-align:center'>".$emp_code."</td>
								<td style='text-align:center'>".$component_value."</td>
								<td style='text-align:center'>".$doj."</td>
								<td style='text-align:center'>".$department."</td>
								<td style='text-align:center'>".$approve_type."</td>
								<td style='text-align:center'>".$first_level_approval."</td>
								<td style='text-align:center'>".$hr_approval."</td>
								<td style='text-align:center'>".$level1."</td>
								<td style='text-align:center'>".$level2."</td>
								<td style='text-align:center'>".$leave_status."</td>
								<td style='text-align:center'>".$applied_on."</td>
							  </tr>";
		  return $emp_list_data;
	}
	//FOR REQUEST AND DIRECT LEAVE ENTRY
	public function view_permission_details($emp_code){
		// $logged_emp_code      	  = $this->session->userdata('logged_emp_code');
		$emp_qry 				  = 'select emp_name from cw_employees where cw_employees.employee_code = "'.$emp_code.'" and cw_employees.trans_status = 1';
		$emp_info       		  = $this->db->query($emp_qry);
		$emp_result  			  = $emp_info->result();
		$emp_info->next_result();
		$emp_name 				  = $emp_result[0]->emp_name;
	
		$permission_entry_qry 	  = 'select permission_date,cw_permission_type.permission_type,cw_shift_master.shift_name,cw_permission_entry.in_time,cw_permission_entry.out_time,total_time,cw_leave_status.leave_status from cw_permission_entry inner join cw_leave_status on cw_leave_status.prime_leave_status_id = cw_permission_entry.leave_status inner join cw_permission_type on cw_permission_type.prime_permission_type_id = cw_permission_entry.permission_type inner join cw_shift_master on cw_shift_master.prime_shift_master_id = cw_permission_entry.shift_name where cw_permission_entry.employee_code = "'.$emp_code.'" and cw_permission_entry.trans_status = 1 ORDER BY prime_permission_entry_id DESC LIMIT 3';
		$permission_entry_info    = $this->db->query($permission_entry_qry);
		$permission_entry_result  = $permission_entry_info->result();
		$permission_entry_info->next_result();

		$table_list = "";	
		if($permission_entry_result[0]->shift_name){
			$rowspan_collumn = "<tr><td rowspan = 3 style = 'text-align:center;'>".$emp_code."</td>
	    	            <td rowspan = 3 style = 'text-align:center;'>".$emp_name."</td>";
		   	$table_list = $rowspan_collumn;	
		  	foreach ($permission_entry_result as $key => $value) {
			  	$permission_date    = date('d-m-Y',strtotime($value->permission_date));
			  	$permission_type    = $value->permission_type;
			  	$shift_name 		= $value->shift_name;
			  	$total_time 		= $value->total_time;
			  	$leave_status 		= $value->leave_status;
				$table_list .= "
			    <td style = 'text-align:center;'>".$permission_date."</td>
			    <td style = 'text-align:center;'>".$value->in_time."</td>
			    <td style = 'text-align:center;'>".$value->out_time."</td>
			    <td style = 'text-align:center;'>".$total_time."</td>
			    <td style = 'text-align:center;'>".$permission_type."</td>
			    <td style = 'text-align:center;'>".$shift_name."</td>
			    <td style = 'text-align:center;'>".$leave_status."</td>
			  </tr>";
			}
		}else{
			$table_list = "<tr><td></td><td></td><td></td><td> No Results Found </td><td></td><td></td><td></td></tr>";
		}
		return $table_list;
	}
	public function cat_last_pay_process_info($starting_date,$ending_date,$category){
		$last_pay_trans_qry  = 'SELECT role as category,date_format(MAX(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y")) , "%m-%Y") AS process_month from cw_transactions where cw_transactions.trans_status = 1 and date_format(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y") , "%Y-%m-%d") >= "'.$starting_date.'" and cw_transactions.role = "'.$category.'"';
		// and date_format(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y") , "%Y-%m-%d") >= "'.$starting_date.'"		
		$last_pay_trans_info = $this->db->query("CALL sp_a_run ('SELECT','$last_pay_trans_qry')");
		$last_pay_trans_rslt = $last_pay_trans_info->result();
		$last_pay_trans_info->next_result();
		$process_month       = $last_pay_trans_rslt[0]->process_month;
		if(!$process_month){
			//THERE IS NO ANY PAYROLL PROCESS MONTH THEN GET FINANCIAL START MONTH
			// $process_month_obj   = (object)array('process_month' => date('m-Y'));
			//THERE IS NO ANY PAYROLL PROCESS MONTH THEN GET FINANCIAL START MONTH
			$process_month_obj   = (object)array('process_month' => date('m-Y',strtotime($starting_date)));
			$process_month_arr   = array(0 => $process_month_obj);
			return $process_month_arr;
		}else{
			return $last_pay_trans_rslt;
		}
	}

	public function validatejunkchar($junk) {
		return preg_match('/[^\x20-\x7E\x09\x0A\x0D\x0C]/', $junk) ?  0 : 1;
	}
	public function validateMobileNumber($number) {
		//return preg_match('/^[6-9](?!.*(\d)\1{4})\d{9}$/', $number) ? 1 : 0;
		return preg_match('/^[6-9](?!.*(\d)\1{8})\d{9}$/', $number) ? 1 : 0; //BSK
	}
	public function validateString($str) {
	    return preg_match('/^[a-zA-Z\s.]+$/', $str) ? 1 : 0;
	}
	public function validateinteger($int){
		return preg_match('/^[0-9]+$/', $int) ? 1: 0;
	}
	public function validateDATE($date) {
    	return preg_match('/^(0[1-9]|[12][0-9]|3[01])[-\/](0[1-9]|1[0-2])[-\/]\d{4}$/', $date) ? 1 : 0;
	}
	public function validatetime($time){
		return preg_match('/^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/', $time) ? 1 : 0;
	}
	public function validateDecimal($input) {
		return preg_match('/^\s*[+\-]?\d+\.\d+\s*$/', $input) ? 1 : 0;
	}
	public function validateYear($year) {
		return preg_match('/^\d{4}$/', $year) ? 1 : 0;
	}
	public function validateDateTime($datetime){
		$dateTimeRegex = '/^(0[1-9]|[12][0-9]|3[01])[-\/](0[1-9]|1[0-2])[-\/]\d{4} (0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/';
		return preg_match($dateTimeRegex, $datetime) ? 1 : 0;
	}
	public function validateMonthYear($monthyear){
		return preg_match('/^(0[1-9]|1[0-2])\/\d{4}$/', $monthyear) ? 1 : 0;
	}
	public function validatePanCard($pan){
		return preg_match('/^[A-Z]{5}\d{4}[A-Z]$/', $pan) ? 1 : 0;
	}	
	public function encryptFilename($data,$key){
	    $method = 'aes-256-gcm'; 
	
	    $key = base64_decode( $key );
	    $iv =  openssl_cipher_iv_length( $method ) ;
	    $tag = ""; // openssl_encrypt will fill this
	    $result = openssl_encrypt( $data , $method , $key , OPENSSL_RAW_DATA , $iv , $tag , "" , 6 );
	     $dirty = array("+", "/", "=");
    	$clean = array("_PLUS_", "_SLASH_", "_EQUALS_");
	    return str_replace($dirty, $clean,base64_encode($iv.$tag.$result ));
	}
	public function ppnDecrypt($data,$key){
	    $method = 'aes-256-gcm';
	    $dirty = array("+", "/", "=");
    	$clean = array("_PLUS_", "_SLASH_", "_EQUALS_");
    	$data= str_replace($clean,$dirty,$data);
	    $data = base64_decode( $data );
	    $key = base64_decode( $key );
	    $ivLength = openssl_cipher_iv_length( $method );
	    $iv = substr( $data , 0 , $ivLength );
	    $tag = substr( $data , $ivLength , 6 );
	    $text = substr( $data , $ivLength+6 );
	    return openssl_decrypt( $text , $method , $key , OPENSSL_RAW_DATA , $iv , $tag );
	}
	// TIME CONVERTION [MS 20-08-2024]
	public function convertDecimalHoursToTime($decimalHours){
		$hours   = floor($decimalHours); 
		$minutes = floor(($decimalHours - $hours) * 60); 
   		// $seconds = floor((($decimalHours - $hours)  60 - $minutes)  60);
		return sprintf('%02d:%02d', $hours, $minutes);
	}
	public function decimalHours($time){
	    $hms = explode(":", $time);
	    return round($hms[0] + ($hms[1]/60) + ($hms[2]/3600),2);
	}

	//Upload Files
	public function upload_files(){
		$encString     = file_get_contents('php://input');
		$_POST         = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
		$send_for      = $this->input->post('send_for'); //import or upload
		$send_from     = $this->input->post('send_from'); //module name
		$file_name     = $this->input->post('fileName');
		$file_data     = base64_decode($this->input->post('file_data'));	
		$finfo         = new finfo(FILEINFO_MIME_TYPE);		
		$file_type     = $finfo->buffer($file_data); // Get the MIME type from the binary data
		if($send_from  === 'offer_upload'){
			$send_from = 'offer_letter';
		}
		// Create directory if not exists
		$upload_dir = "upload_files/$send_from";
		if(($send_for !== "") && ($send_from !== "")){
			if(!file_exists($upload_dir)){
				mkdir($upload_dir, 0755, true);
				chmod($upload_dir, 0755);
			}
			// Ensure the directory is writable
			if (!is_writable($upload_dir)) {
				echo json_encode(array('success' => false, 'msg' => "Error: Upload directory is not writable."));
				exit(0);
			}
			$label_id         = $this->input->post('label_id');				
			$file_size        = $this->input->post('size');
			//MIME Types
			$mime_types = [ 'jpg'  => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png'  => 'image/png', 'gif'  => 'image/gif', 'html' => 'text/html', 'pdf'  => 'application/pdf', 'doc'  => 'application/msword', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'xls'  => 'application/vnd.ms-excel', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'mp3'  => 'audio/mpeg', 'mp4'  => 'video/mp4', 'zip'  => 'application/zip', 'txt'  => 'text/plain','msg'  => 'application/vnd.ms-outlook','eml' => 'message/rfc822'];

			//Get info from Form Settings
			$from_query = 'select upload_extension,upload_file_size from cw_form_setting  where prime_module_id = "'.$send_from.'" and field_show = "1" and field_type = 10 and label_name = "'.$label_id.'" and trans_status = "1" and FIND_IN_SET("'.$this->logged_role.'",field_for) ORDER BY input_for,field_sort asc';
			$form_data        = $this->db->query("CALL sp_a_run ('SELECT','$from_query')");
			$form_result      = $form_data->result();
			$form_data->next_result();
			if(count($form_result ?? []) === 0){
				echo json_encode(array('success' => false, 'msg' =>"URL Expired.. Please Referesh the Page and retry.."));
				exit(0);
			}
			$upload_filesize  = $form_result[0]->upload_file_size;
			$upload_extension = $form_result[0]->upload_extension;
			$allowed_ext      = explode(",",$upload_extension);	
			// Find elements in $array1 that match the keys in $array2
			$array_flip       = array_flip($allowed_ext);
			$allowed_mimes    = array_intersect_key($mime_types,$array_flip);

			if (!in_array($file_type, $allowed_mimes)) {
				echo json_encode(array('success' => false, 'msg' =>"Please upload valid Mime type file such as $upload_extension"));
				exit(0);
			}
			$file_name        = str_replace(" ","_", $file_name);
			$file_size        = $file_size/1000;
			if((int)$upload_filesize === 0){
				$upload_filesize = 500;
			}
			if((int)$file_size <= (int)$upload_filesize){
				if($file_name){
					$ext = pathinfo($file_name, PATHINFO_EXTENSION);
					if(in_array($ext, $allowed_ext)){
						$random_digit  = rand(0000,99999999999);
						$new_file_name = "upload_files/$send_from/".$random_digit."_".$file_name;
						$path          = $this->sanitize_input($new_file_name, 10);	
						file_put_contents($path, $file_data);		
						echo json_encode(array('success' => true, 'msg' =>"File moved to server","path"=>$path));
					}else{
						echo json_encode(array('success' => false, 'msg' =>"Please upload valid file such as $upload_extension"));
					}
				}else{
					echo json_encode(array('success' => false, 'msg' =>"Please upload valid file"));
				}
			}else{
				echo json_encode(array('success' => false, 'msg' =>"File Size Must be below ".$upload_filesize."kb"));
			}
		}else{
			echo json_encode(array('success' => false, 'msg' =>"Please refresh page and retry"));
		}
	}
	//Import Operation
	public function import_file(){
		$encData   = $this->input->post('Payload');
		$_POST     = $this->cryptoDecrypt($encData);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'URL Expired.. Please Referesh the Page and retry..','table_data' => ""));
			exit(0);
		}
	
		$send_from = $this->input->post('send_from');
		$send_for  = $this->input->post('send_for');
		$fileName  = $this->input->post('fileName');
		$size      = $this->input->post('size');
		//Get File MIME Type	
		$allowed_ext      = array('xls','xlsx');
		$finfo            = finfo_open(FILEINFO_MIME_TYPE);
		$file_type        = finfo_file($finfo, $_FILES['excel_select_file']['tmp_name']);
		finfo_close($finfo);
		$mime_types = [ 'xls'  => 'application/vnd.ms-excel', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
		if (!in_array($file_type, $mime_types)) {
			echo json_encode(array('success' => false, 'msg' =>"Please upload valid Mime type file such as ".implode(",",$allowed_ext)));
			exit(0);
		}
		if($fileName !== $_FILES['excel_select_file']['name'] || $size !== $_FILES['excel_select_file']['size']){
			echo json_encode(array('success' => false,'message' => 'Invalid File..','table_data' => ""));
			exit(0);
		}
		$oldmask = umask(0);
		if(!file_exists("./upload_files/$send_from/$send_for")){
			mkdir("./upload_files/$send_from/$send_for", 0755, true);
			chmod("./upload_files/$send_from/$send_for", 0755);
		}
		umask($oldmask);		
		$file_name     = str_replace("'","",$_FILES['excel_select_file']['name']);
		$ext           = pathinfo($file_name, PATHINFO_EXTENSION);		
		if(in_array($ext, $allowed_ext)){
			$random_digit  = rand(0000,99999999999);
			$new_file_name = $random_digit."_".$file_name;
			$path          = $this->sanitize_input("upload_files/$send_from/$send_for/".$new_file_name, 10);

			// Ensure the directory is writable
			if(!is_writable("./upload_files/$send_from/$send_for")){
				echo json_encode(array('success' => false, 'msg' =>"Error: Upload directory is not writable"));
				exit(0);
			}
			// $path = $path . basename($_FILES['excel_select_file']['name']);
			// print_r($path);die;

			if (move_uploaded_file($_FILES['excel_select_file']['tmp_name'], "./".$path)) {
				echo json_encode(array('success' => true, 'msg' =>"File has been selected","path"=>$path));
			} else {
				echo json_encode(array('success' => false, 'msg' =>"Error uploading file"));
			}
		}else{
			echo json_encode(array('success' => false, 'msg' =>"Please upload valid file"));
		}
	}
	public function sanitize_input($input, $field_type){
		switch ($field_type){
			case 3 ://INT
			case 11://Mobile Number
				// Sanitize integer values
				return filter_var($input, FILTER_SANITIZE_NUMBER_INT);			
			case 2://Decimal
				// Sanitize float values
				return filter_var($input, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);	
			case 12://email
				// Sanitize and validate email
				$sanitized_email = filter_var($input, FILTER_SANITIZE_EMAIL);
				return filter_var($sanitized_email, FILTER_VALIDATE_EMAIL) ? $sanitized_email : null;			
			case 10://url
				// Sanitize and validate URL
				$sanitized_url = filter_var($input, FILTER_SANITIZE_URL);
            	return $sanitized_url;
				//return filter_var($sanitized_url, FILTER_VALIDATE_URL) ? $sanitized_url : null;
	
			case 'array'://url
				// Sanitize each element in an array recursively
				if(is_array($input)){
					return array_map(function($item) {
						$sanitized_string = filter_var($item, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_NO_ENCODE_QUOTES);
						return htmlspecialchars($sanitized_string, ENT_QUOTES, 'UTF-8');
					}, $input);
				}
				return null;
	
			case 1://TEXT
			case 4://DATE
			case 5://PICKLIST
			case 6://CHECKBOX
			case 7://MULTIPICK
			case 8://SUMMARY
			case 9://AUTOCOMPLETE
			case 10://FILE UPLOAD
			case 13://DATE & TIME
			case 15://TIME
			default:
				// Sanitize general strings (strips HTML tags, encodes special characters)
				$sanitized_string = filter_var($input, FILTER_SANITIZE_FULL_SPECIAL_CHARS, FILTER_FLAG_NO_ENCODE_QUOTES);
				return str_replace(['&amp;', '&#38;'], '&', $sanitized_string);
		}
	}
	//Generate Key
	// public function generateKey(){
	// 	$sess_id        = $this->session->userdata('__ci_last_regenerate');
	// 	$employee_code  = $this->session->userdata('logged_emp_code');
	// 	$encKey         = $this->config->item("encKey");
	// 	$combineKey     = $sess_id."||".$employee_code."||".$encKey;
	// 	$key            = hash('sha512', $combineKey);
	// 	return $key;
	// }
	// //Decrypt Encrypted string from Javascript
	// public function cryptoDecrypt($encString){
	// 	try{
	// 		$key            = $this->generateKey();
	// 		$password       = hash('sha512', $key);
	// 		$keySize        = 256;
	// 		$iterations     = 1000;
	// 		$decSalt        = substr($encString, 0, 32);
	// 		$decIvhex       = substr($encString, 32, 32);
	// 		$encrypted      = substr($encString, 64);
	// 		$decKey         = hash_pbkdf2( 'sha1', $password, hex2bin($decSalt), $iterations, $keySize / 8, true);
	// 		// AES decryption using OpenSSL in PHP
	// 		$decrypted      = openssl_decrypt(
	// 			base64_decode($encrypted),  // Encrypted data (decode from Base64)
	// 			'AES-256-CBC',              // Cipher method (AES-256-CBC for 256-bit key size)
	// 			$decKey,                    // Decryption key
	// 			OPENSSL_RAW_DATA,           // Options: raw data output
	// 			hex2bin($decIvhex)          // Initialization vector
	// 		);		
	// 		if(!$decrypted){
	// 			throw new Exception('Error0001..');
	// 		}else{
	// 			return json_decode($decrypted,TRUE);
	// 		}			
	// 	}catch(Exception $e){
	// 		$to_email = $this->config->item("to_email");
	// 		$cc_email = $this->config->item("cc_email");
	// 		$content = "Hi, Unautherised Attempt happened from the login ".$this->session->userdata('logged_emp_code')." at ".date("d-m-Y H:i:s").". Please find the string below '$encString'";
	// 		$this->send_email_notification($to_email,"","",$cc_email,"Unauthorized Attempt",$content,"");
	// 		// Log the error or handle it as needed
	// 		error_log("Decryption Error: " . $e->getMessage()); // Log the error for debugging
	// 		echo json_encode(array('success' => false,'message' => 'Timeout..Please Refresh and retry Again...'));
	// 		//$this->session->sess_destroy();
	// 		//redirect('login');
	// 		exit(0);
	// 		return false;		
	// 	}	
	// }

	//GET TOTAL WORKING DAYS
	public function get_total_work_days($role,$process_month){
		$month_day_result   = $this->month_day_qry_fun($role);
		if($month_day_result){			
			$role           = $month_day_result[0]->category;
			$day_conditions = $month_day_result[0]->day_conditions;
			$day_count      = $month_day_result[0]->day_count;
			$day_start      = $month_day_result[0]->day_start;
			$day_end        = $month_day_result[0]->day_end;
			$month_day = array();
			if((int)$day_conditions === 1){
				//STATIC DAYS
				$month_day = $day_count;
			}else
			if((int)$day_conditions === 2){
				//CALENDER DAYS
				$trans_month = explode("-",$process_month);
				$month_val     = $trans_month[0];
				$year_val      = $trans_month[1];
				$day_count     = cal_days_in_month(CAL_GREGORIAN, $month_val, $year_val);
				$month_day     = $day_count;
			}else
			if((int)$day_conditions === 3){
				//CUTOFF DAYS
				$trans_month   = explode("-",$process_month);
				$month_val     = $trans_month[0];
				$year_val      = $trans_month[1];
				$pre_month     = (int)$month_val - 1;
				$pre_year_val  = $year_val;
				if((int)$pre_month === 0){
					$pre_month     = 12;
					$pre_year_val  = (int)$year_val - 1;
				}
				$start_date = $day_start."-".$pre_month."-".$pre_year_val;
				$end_date   = $day_end."-".$month_val."-".$year_val;
				$start_date = strtotime($start_date);
				$end_date   = strtotime($end_date);
				$datediff   = $end_date - $start_date;
				$day_count  = round($datediff/86400);//60 * 60 * 24
				$month_day  = (int)$day_count + 1;
			}
		}else{
			$trans_month = explode("-",$process_month);
			$month_val     = $trans_month[0];
			$year_val      = $trans_month[1];
			$day_count     = cal_days_in_month(CAL_GREGORIAN, $month_val, $year_val);
			$month_day     = $day_count;
		}		
		return $month_day;
	}

	   //FUNCTION FOR CHECK A CATEGORY ADDED OR NOT IN STATUTORY AND GRATUITY SETTINGS MODULE
    public function cat_settings_err($cat_set_rslt,$category_arr,$cat_data){
        $cat_set_err_data   = "";
        $cat_set_arr        = array_column($cat_set_rslt, 'category');
        $cat_set_err_arr    = array_diff($category_arr,$cat_set_arr);
        if(!empty($cat_set_err_arr)){
            $cat_set_err_data  = implode(",",array_map(function($v) use(&$cat_data){
                return $cat_data[$v];
            }, $cat_set_err_arr) ?? []);
        }
        return $cat_set_err_data;
    }

	 //CATEGORY BASED STATUTORY SETTINGS VALIDATE FUNCTION
    public function statutory_setting_validate($ear_ded_col_arr,$category_arr,$cat_data){
        $rslt_array        = array();
        //GET CATEGORY BASED STATUTORY SETTINGS ARRAY
        $statuory_set_qry  = 'select prime_statutory_id,category,esi_eligibilit_formula from cw_statutory where cw_statutory.trans_status = 1';
        $statuory_set_data = $this->db->query("CALL sp_a_run ('SELECT','$statuory_set_qry')");
        $statuory_set_rslt = $statuory_set_data->result_array();
        $statuory_set_data->next_result();
        $statuory_err_data = $this->cat_settings_err($statuory_set_rslt,$category_arr,$cat_data);
        if($statuory_err_data){
            $rslt_array     = array('success' => FALSE, 'message' => "Please Map Statutory Settings for the Category of $statuory_err_data");
            
            return $rslt_array;
        }else{
            //CATEGORY BASED STATUATORY FORMULA COLUMNS CHECKING(MATCHING)   
            $stat_cat_col_arr     = array_column($statuory_set_rslt,'esi_eligibilit_formula','category');
            //FUNCTION CALL
            $stat_label_col_arr   = $this->formula_label_match($stat_cat_col_arr,$ear_ded_col_arr,$cat_data);
            $cat_err_name         = $stat_label_col_arr['cat_err_name'];
            $lable_err_name       = $stat_label_col_arr['lable_err_name'];
            
            if($cat_err_name && $lable_err_name){
                $rslt_array     = array('success' => FALSE,'message' => "Unknown Column's $lable_err_name are mapped for the Category's $cat_err_name in Statutory Settings Module.!");

                return $rslt_array;  
            }else{
                return $rslt_array;
            }
        }
    }
	 //CATEGORY BASED GRATUITY SETTINGS VALIDATE FUNCTION
    public function gratuity_setting_validate($ear_ded_col_arr,$category_arr,$cat_data){
        $rslt_array        = array();
        //GET CATEGORY BASED GRATUITY SETTINGS ARRAY
        $gratuity_set_qry  = 'select prime_gratuity_id,category,formula_detail from cw_gratuity where cw_gratuity.trans_status = 1';
        $gratuity_set_data = $this->db->query("CALL sp_a_run ('SELECT','$gratuity_set_qry')");
        $gratuity_set_rslt = $gratuity_set_data->result_array();
        $gratuity_set_data->next_result();

        $gratuity_err_data = $this->cat_settings_err($gratuity_set_rslt,$category_arr,$cat_data);
        if($gratuity_err_data){
            $rslt_array     = array('success' => FALSE, 'message' => "Please Map Gratuity Settings for the Category of $gratuity_err_data");

            return $rslt_array;
        }else{
            //CATEGORY BASED GRATUITY FORMULA COLUMNS CHECKING(MATCHING)   
            $grat_cat_col_arr   = array_column($gratuity_set_rslt,'formula_detail','category');
            //FUNCTION CALL
            $grat_label_col_arr = $this->formula_label_match($grat_cat_col_arr,$ear_ded_col_arr,$cat_data);
            $cat_err_name         = $grat_label_col_arr['cat_err_name'];
            $lable_err_name       = $grat_label_col_arr['lable_err_name'];
    
            if($cat_err_name && $lable_err_name){
                $rslt_array    =  array('success' => FALSE,'message' => "Unknown Column's $lable_err_name are mapped for the Category's $cat_err_name in Gratuity Settings Module.!");

                return $rslt_array;
            }else{
                return $rslt_array;
            }
        }
    }
	
	//FUNCTION FOR CHECK AND MATCH A STATUTORY AND GRATUITY FORMULA COLUMNS BASED ON EARNINGS AND DEDUCTIONS 
    public function formula_label_match($cat_formula_col_arr,$ear_ded_col_arr,$cat_data){
        $cat_err_name     = '';   
        $lable_err_name   = '';   
        foreach($cat_formula_col_arr as $cat_key => $label_val){
            $preg_match      = preg_match_all('#\@(.*?)\@#', $label_val, $match);
            $error           = 0;
            foreach($match[1] as $for_rslt){  
                if($for_rslt){
                    if (!in_array($for_rslt, $ear_ded_col_arr)){
                        $lable_err_name .= $for_rslt.",";
                        $error           = 1;
                    }
                }  
            }
            //Category Name get only once from a row so
            if($cat_data[$cat_key] && $error === 1){
                $cat_err_name    .= $cat_data[$cat_key].","; 
            }
        }  

        if($cat_err_name && $lable_err_name){
            $cat_err_name     = rtrim($cat_err_name, ",");
            $lable_err_name   = rtrim($lable_err_name, ",");
        }
        return array("cat_err_name" => $cat_err_name,"lable_err_name" => $lable_err_name);
    }

	//EMPLOYEES TABLE LOG FOR EVERY UPFDATE OF THE EMPLOYEES
	public function employee_log($emp_id, $emp_log){
		$created_on = date("Y-m-d H:i:s");
		$logged_id  = $this->logged_id;

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

		// =========================
		// INSERT LOG
		// =========================
		if((int)$emp_id === 0){
			foreach($emp_log as $emp_key => $new_label_val){
				if($new_label_val !== '' && $new_label_val !== null) {
					$emp_id           = 0;
					$emp_code         = $emp_log['employee_code'] ?? '';
    				$emp_name         = $emp_log['emp_name'] ?? '';
					$old_labelval     = '';
					$prime_qry_value .= "(\"$emp_id\",\"$emp_code\",\"$emp_name\",\"$emp_key\",\"$old_label_val\",\"$new_label_val\",\"$logged_id\",\"$created_on\"),";
				}
			}
		}else{
			// =========================
			// UPDATE LOG
			// =========================
			$emp_label_name       = array_keys($emp_log);
			if(!in_array('emp_name', $emp_label_name)){
				$emp_label_name[] = 'emp_name';
			}
			if(!in_array('employee_code', $emp_label_name)){
				$emp_label_name[] = 'employee_code';
			}

			$emp_label_value = implode(",",$emp_label_name);
			$emp_data_qry    = "select $emp_label_value from cw_employees where prime_employees_id = $emp_id";

			$emp_data   = $this->db->query("CALL sp_a_run ('SELECT','$emp_data_qry')");
			$emp_result = $emp_data->result_array();
			$emp_data->next_result();

			$fin_emp_result = $emp_result[0]; 
			$emp_code       = $fin_emp_result['employee_code'];
			$emp_name       = $fin_emp_result['emp_name'];

			foreach($emp_log as $emp_key => $new_label_val){
				$old_label_val      = $fin_emp_result[$emp_key] ?? '';
				if(($old_label_val != $new_label_val) && ($new_label_val != '') && ($new_label_val !== '0000-00-00')){
					$prime_qry_value .= "(\"$emp_id\",\"$emp_code\",\"$emp_name\",\"$emp_key\",\"$old_label_val\",\"$new_label_val\",\"$logged_id\",\"$created_on\"),";
				}
			}
		}
		// =========================
		// FINAL INSERT
		// =========================
		if(!empty($prime_qry_value)){
			$prime_qry_value    = rtrim($prime_qry_value,',');
			$prime_insert_query = "insert into cw_employees_log ($prime_qry_key) values $prime_qry_value";
			$insert_info        = $this->db->query("CALL sp_a_run ('INSERT','$prime_insert_query')"); 
			$insert_result      = $insert_info->result(); 
			$insert_info->next_result();
		}
	}

	// ============= GET REQUEST EMPLOYEE DATA FOR FETCH THE DETAILS ================
	public function get_request_employee_data($emp_code,$prime_id){
		if($this->control_name === "claim_approval"){
			$clm_apr_qry        = "SELECT prime_claim_request_id FROM cw_claim_approval WHERE trans_status = 1 AND prime_claim_approval_id = '$prime_id'";
			$clm_apr_data       = $this->db->query($clm_apr_qry);
			$clm_data           = $clm_apr_data->result();
			$clm_apr_data->next_result();	
			$prime_id           = $clm_data[0]->prime_claim_request_id;
			
		}

		$emp_details_qry      = "SELECT e.employee_code,e.emp_name,cwc.category_name FROM cw_employees e INNER JOIN cw_category cwc ON cwc.prime_category_id = e.role WHERE e.trans_status = 1 AND e.termination_status = 0 AND e.employee_code = '$emp_code'";
		$emp_data             = $this->db->query($emp_details_qry);
		$emp_result           = $emp_data->result();
		$emp_data->next_result();	
		$emp_code             = $emp_result[0]->employee_code;
		$emp_name             = $emp_result[0]->emp_name;
		$category             = $emp_result[0]->category_name;

		$clm_req_qry = "SELECT csr.claim_status,ccr.claim_id FROM cw_claim_request ccr INNER JOIN cw_claim_status csr ON csr.prime_claim_status_id = ccr.claim_status WHERE ccr.trans_status = 1 AND ccr.prime_claim_request_id = '$prime_id'";
		$clm_req_data         = $this->db->query($clm_req_qry);
		$clm_req_result       = $clm_req_data->result();
		$clm_req_data->next_result();	
		$claim_status         = $clm_req_result[0]->claim_status;
		$claim_id             = $clm_req_result[0]->claim_status;
		$emp_list_data        = "";
		$claim_status         = !empty($claim_status) ? $claim_status : "Pending";

		$emp_map_qry    = "SELECT em.approval_type,CONCAT(e1.employee_code, ' - ', e1.emp_name) AS level1_name,CONCAT(e2.employee_code, ' - ', e2.emp_name) AS level2_name,CONCAT(e3.employee_code, ' - ', e3.emp_name) AS level3_name,cs1.claim_status AS level1_status,cs2.claim_status AS level2_status,cs3.claim_status AS level3_status FROM cw_employee_mapping em LEFT JOIN cw_employees e1 ON e1.employee_code = em.level1 LEFT JOIN cw_employees e2 ON e2.employee_code = em.level2 LEFT JOIN cw_employees e3 ON e3.employee_code = em.level3 LEFT JOIN cw_claim_approval ccr ON ccr.employee_code = em.employee_code AND ccr.prime_claim_request_id = '$prime_id' AND ccr.trans_status = 1 LEFT JOIN cw_claim_status cs1 ON cs1.prime_claim_status_id = ccr.level1_approval_status LEFT JOIN cw_claim_status cs2 ON cs2.prime_claim_status_id = ccr.level2_approval_status LEFT JOIN cw_claim_status cs3 ON cs3.prime_claim_status_id = ccr.level3_approval_status WHERE em.trans_status = 1 AND em.employee_code = '$emp_code'";
		$emp_map_data             = $this->db->query($emp_map_qry);
		$emp_map_result           = $emp_map_data->result();
		
		$emp_map_data->next_result();
		$approval_type            = $emp_map_result[0]->approval_type;
		$level1_name              = $emp_map_result[0]->level1_name;
		$level2_name              = $emp_map_result[0]->level2_name;
		$level3_name              = $emp_map_result[0]->level3_name;
		$level1_status            = $emp_map_result[0]->level1_status;
		$level2_status            = $emp_map_result[0]->level2_status;
		$level3_status            = $emp_map_result[0]->level3_status;
			
		$emp_list_data   = "<tr>
							<td style='text-align:center'>".$emp_code."</td>
							<td style='text-align:center'>".$emp_name."</td>
							<td style='text-align:center'>".$category."</td>
						
						";
		$levels = [1 => [$level1_name, $level1_status],2 => [$level2_name, $level2_status],3 => [$level3_name, $level3_status],];
		for($i = 1; $i <= $approval_type; $i++){
			$emp_list_data .= "
				<td style='text-align:center'>{$levels[$i][0]}</td>
				<td style='text-align:center'>{$levels[$i][1]}</td>
			";
		}

		$emp_list_data .= "
			<td style='text-align:center'>{$claim_status}</td>
		</tr>";
		
		return $emp_list_data;
	}
	// ==================================== SHIFT CONFIG IMPORT  ========================================
	public function do_config_import($import_id){
		if($import_id < 0){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}
		
		$excel_path_qry    = 'select * from cw_import where import_id = "'.$import_id.'"';
		$excel_path_info   = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
		$excel_path_result = $excel_path_info->result();
		$excel_path_info->next_result();
		if(!$excel_path_result){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}else{
			$excel_file_path    = $excel_path_result[0]->excel_file_path;
			$module_id          = $excel_path_result[0]->module_id;
			$excel_format       = $excel_path_result[0]->excel_format;
			$excel_sheet_name   = (int)$excel_path_result[0]->excel_sheet_name;
			$excel_row_start    = (int)$excel_path_result[0]->excel_start_row;
			$excel_row_end      = (int)$excel_path_result[0]->excel_end_row;
			
			$format_qry 	= 'select * from cw_util_excel_format where prime_excel_format_id = "'.$excel_format.'" and cw_util_excel_format.trans_status = 1';
			$format_info    = $this->db->query("CALL sp_a_run ('SELECT','$format_qry')");
			$format_rslt    = $format_info->result();
			$format_info->next_result();
			if(!$format_rslt){
				return json_encode(array('success' => false, 'message' => "Please add excel format before import"));
			}else{
				$exist_column_name  = explode(",",$format_rslt[0]->exist_column_name);
				$excel_format_qry 	= 'select field_type,pick_table,pick_list_type,pick_list_import,pick_list,mandatory_field,field_isdefault,excel_line_column_name,excel_line_value,label_name,view_name,unique_field from cw_util_excel_format_line inner join cw_form_setting on label_name = excel_line_column_name where excel_line_module_id = "'.$module_id.'" and prime_excel_format_id = "'.$excel_format.'" and cw_form_setting.prime_module_id = "'.$module_id.'" and cw_util_excel_format_line.trans_status = 1';			
				$excel_format        = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
				$excel_format_result = $excel_format->result();
				$excel_format->next_result();

				// GET ACTIVE & DEVICE CODE MAPPED 
				$emp_code_qry   = "SELECT employee_code,device_code FROM cw_employees WHERE trans_status = 1 
                AND termination_status = 0";
				$emp_code_info  = $this->db->query("CALL sp_a_run('SELECT', '$emp_code_qry')");
				$employee_codes = $emp_code_info->result();
				$emp_code_info->next_result();	
				$employee_device_map = [];
				foreach($employee_codes as $row){
					$employee_device_map[$row->employee_code] = $row->device_code;
				}

				if(!$excel_format_result){
					return json_encode(array('success' => false, 'message' => "Please map excel cell column before import"));
				}
				else{
					try{
						$excel_obj = \PhpOffice\PhpSpreadsheet\IOFactory::load($excel_file_path);
					}catch(Exception $e){
						die('Error loading file "' . pathinfo($excel_file_path, PATHINFO_BASENAME). '": ' . $e->getMessage());
						return json_encode(array('success' => false, 'message' => "Invalid file or path"));
					}
					$sheet           = $excel_obj->getSheet($excel_sheet_name);
					if($excel_row_end){
						$total_rows  = $excel_row_end;
					}else{
						$total_rows  = $sheet->getHighestRow();
					}
					$highest_column      = $sheet->getHighestColumn();
					$worksheetTitle      = $sheet->getTitle();
					$insert_qry          = array();
					$insert_value_qry    = array();
					$update_qry          = array();
					$exits_qry           = array();
					$employee_code_list  = array();
					$effective_dates     = array();
					$temp_insert_data    = array();
					for($row = $excel_row_start; $row <= $total_rows; $row++){
						$sts                        = TRUE;
						$mobile_sts                 = TRUE;
						$email_sts                  = TRUE;
						$effective_date             = "";
						$employee_code              = "";
						$prime_column_val           = "";
						$prime_cell_val             = "";
						$exist_val                  = "";
						$upd_qry_build              = "";
						$applicable_shifts          = array();
						$default_shifts             = array();
						$shift_type                 = "";    
						$week_off_type              = "";   
						$applicable_week_off        = "";
						foreach($excel_format_result as $excel_info){
							$field_isdefault        = (int)$excel_info->field_isdefault;
							$mandatory_field        = (int)$excel_info->mandatory_field;
							$field_type             = (int)$excel_info->field_type;
							$pick_table             = $excel_info->pick_table;
							$pick_list_type         = (int)$excel_info->pick_list_type;
							$pick_list_import       = (int)$excel_info->pick_list_import;
							$pick_list              = $excel_info->pick_list;
							$excel_line_column_name = $excel_info->excel_line_column_name;
							$excel_line_value       = $excel_info->excel_line_value;
							$get_cell_value         = ucwords(trim($sheet->getCell("$excel_line_value$row")->getValue()));
                            if($get_cell_value){
								//FOR MOBILE NUMBER
								if($field_type === 11){
									$length           = strlen($get_cell_value);
									$length_query     = 'select field_length from cw_form_setting where cw_form_setting.prime_module_id = "'.$module_id.'" and cw_form_setting.field_type = 11';
									$length_data      = $this->db->query("CALL sp_a_run ('SELECT','$length_query')");
									$length_result    = $length_data->result();
									$length_data->next_result();
									$field_length     = $length_result[0]->field_length;
									if($field_length != $length){
										$sts          = FALSE;
									}else{
										// VALIDATE MOBILE NUMBER 
										if((int)$this->validateMobileNumber($get_cell_value) === 0){
    										$mobile_sts = FALSE;
										}else{
											$mobile_sts = TRUE;
										}		
									}
								}else 
								if($field_type === 12){
									//FOR EMAIL
									$email         = $get_cell_value;
									if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
										$email_sts = FALSE;
									}
								}else
								if($field_type === 4){
									// FOR DATE
									$cell = trim($sheet->getCell("$excel_line_value$row")->getValue());
									if(is_numeric($cell)){
										try{
											$get_cell_value = Date::excelToDateTimeObject($cell)->format('Y-m-d');
										}catch(Exception $e){
											$err_column_array['error']["$excel_line_value$row"] = "Invalid Excel Date";
											continue;
										}
									}else{
										if($cell == '00-00-0000' || $cell == '0000-00-00'){
											$err_column_array['error']["$excel_line_value$row"] = "Invalid Date (00-00-0000 not allowed)";
											continue;
										}
										$date = DateTime::createFromFormat('d-m-Y', $cell);

										if(!$date || $date->format('d-m-Y') !== $cell){
											$err_column_array['error']["$excel_line_value$row"] = "Invalid Date Format";
											continue;
										}
										$get_cell_value = $date->format('Y-m-d');
									}
								}else
								if($field_type === 13){
									$get_date_time 	= $sheet->getCell("$excel_line_value$row")->getValue();
									$date 			= DateTime::createFromFormat('d/m/Y H:i:s A', $get_date_time);
									$get_cell_value = $date->format('Y-m-d H:i:s');
								}else
								if($field_type === 7){ // FOR PICKLIST CHECK
									if($pick_list_type === 1){
										$pick_list_val   = explode(",",$pick_list);
										$pick_list_val_1 = $pick_list_val[0];
										$pick_list_val_2 = $pick_list_val[1];
										$values          = array_map('trim', explode(',', $get_cell_value));
										$final_ids       = [];

										foreach($values as $val){
											if($pick_list_import === 1){
												$pick_query = 'select '.$pick_list.',trans_status from '.$pick_table.' where '.$pick_list_val_1.' = "'.$val.'"';	
											}else{
												$pick_query = 'select '.$pick_list.',trans_status from '.$pick_table.' where '.$pick_list_val_2.' = "'.$val.'"';
											}	
											$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
											$pick_result = $pick_data->result();
											$pick_count  = $pick_data->num_rows();
											$pick_data->next_result();
											if((int)$pick_count === 0 && $mandatory_field === 0){
												if($pick_table !== $this->prime_table){
													$ins_query  = 'insert into '.$pick_table.'('.$pick_list_val_2.') VALUES ("'.$val.'")';
													$ins_info   = $this->db->query("CALL sp_a_run ('INSERT','$ins_query')");
													$ins_result = $ins_info->result();
													$ins_info->next_result();
													$final_ids  = $ins_result[0]->ins_id;
												}
											}else
											if((int)$pick_count === 0 && $mandatory_field === 1){
												$err_column_array['error']["$excel_line_value$row"]  = "Invalid $val";
											}else
											if((int)$pick_count === 1){
												if($pick_table !== $this->prime_table){
													$pick_id     = $pick_result[0]->$pick_list_val_1;
													$pick_status = (int)$pick_result[0]->trans_status;
													if($pick_status === 0 && $mandatory_field === 1){
														$err_column_array['error']["$excel_line_value$row"]  = "Invalid $val";
													}else
													if($pick_status === 0 && $mandatory_field === 0){
														$upd_query  = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = '.$pick_id;
														$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
														$final_ids[] = $pick_id;
													}else
													if($pick_status === 1){
														$final_ids[] = $pick_id;
													}
												}
											}else
											if($pick_list_type === 2){
												$pick_list_val_1 = $pick_table."_id";
												$pick_list_val_2 = $pick_table."_value";
												$pick_list_val_3 = $pick_table."_status";
												$pick_query      = 'select * from '.$pick_table.' where '.$pick_list_val_2.' = "'.$val.'"';
												$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
												$pick_result = $pick_data->result();
												$pick_count  = $pick_data->num_rows();
												$pick_data->next_result();
												if((int)$pick_count === 0 && $mandatory_field === 0){
													$ins_query   = 'insert into '.$pick_table.'('.$pick_list_val_2.') VALUES ("'.$val.'")';
													$ins_info    = $this->db->query("CALL sp_a_run ('INSERT','$ins_query')");
													$ins_result  = $ins_info->result();
													$ins_info->next_result();
													$final_ids[] = $ins_result[0]->ins_id;
												}else
												if((int)$pick_count === 0 && $mandatory_field === 1){
													$err_column_array['error']["$excel_line_value$row"]   = "Invalid $val";
												}else
												if((int)$pick_count === 1){
													$pick_id     = $pick_result[0]->$pick_list_val_1;
													$pick_status = (int)$pick_result[0]->$pick_list_val_3;
													if($pick_status === 0 && $mandatory_field === 1){
														$err_column_array['error']["$excel_line_value$row"] = "Invalid $val";
													}else
													if($pick_status === 0 && $mandatory_field === 0){
														$upd_query  = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = '.$pick_id;
														$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
														$final_ids[] = $pick_id;
													}else
													if($pick_status === 1){
														$final_ids[] = $pick_id;
													}
												}
											}
										}
										// FINAL VALUE STORED IN EMPLOYEE
										$get_cell_value = implode(',', $final_ids);
									}
								}else		      
								if(($field_type === 5)){
									if($pick_list_type === 1){
										$pick_list_val   = explode(",",$pick_list);
										$pick_list_val_1 = $pick_list_val[0];
										$pick_list_val_2 = $pick_list_val[1];
										if($pick_list_import === 1){
											$pick_query = 'select '.$pick_list.',trans_status from '.$pick_table.' where '.$pick_list_val_1.' = "'.$get_cell_value.'"';	
										}else{
											$pick_query = 'select '.$pick_list.',trans_status from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
										}	
										$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
										$pick_result = $pick_data->result();
										$pick_count  = $pick_data->num_rows();
										$pick_data->next_result();
										if((int)$pick_count === 0 && $mandatory_field === 0){
											if($pick_table !== $this->prime_table){
												$ins_query  = 'insert into '.$pick_table.'('.$pick_list_val_2.') VALUES ("'.$get_cell_value.'")';
												$ins_info   = $this->db->query("CALL sp_a_run ('INSERT','$ins_query')");
												$ins_result = $ins_info->result();
												$ins_info->next_result();
												$get_cell_value  = $ins_result[0]->ins_id;
											}
										}else
										if((int)$pick_count === 0 && $mandatory_field === 1){
											$err_column_array['error']["$excel_line_value$row"]  = "Invalid $get_cell_value";
										}else
										if((int)$pick_count === 1){
											if($pick_table !== $this->prime_table){
												$pick_id     = $pick_result[0]->$pick_list_val_1;
												$pick_status = (int)$pick_result[0]->trans_status;
												if($pick_status === 0 && $mandatory_field === 1){
													$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
												}else
												if($pick_status === 0 && $mandatory_field === 0){
													$upd_query  = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = '.$pick_id;
													$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
													$get_cell_value = $pick_id;
												}else
												if($pick_status === 1){
													$get_cell_value = $pick_id;
												}
											}
										}
									}else
									if($pick_list_type === 2){
										$pick_list_val_1 = $pick_table."_id";
										$pick_list_val_2 = $pick_table."_value";
										$pick_list_val_3 = $pick_table."_status";
										$pick_query      = 'select * from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
										$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
										$pick_result = $pick_data->result();
										$pick_count  = $pick_data->num_rows();
										$pick_data->next_result();
										if((int)$pick_count === 0 && $mandatory_field === 0){
											$ins_query  = 'insert into '.$pick_table.'('.$pick_list_val_2.') VALUES ("'.$get_cell_value.'")';
											$ins_info   = $this->db->query("CALL sp_a_run ('INSERT','$ins_query')");
											$ins_result = $ins_info->result();
											$ins_info->next_result();
											$get_cell_value  = $ins_result[0]->ins_id;
										}else
										if((int)$pick_count === 0 && $mandatory_field === 1){
											$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
										}else
										if((int)$pick_count === 1){
											$pick_id     = $pick_result[0]->$pick_list_val_1;
											$pick_status = (int)$pick_result[0]->$pick_list_val_3;
											if($pick_status === 0 && $mandatory_field === 1){
												$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
											}else
											if($pick_status === 0 && $mandatory_field === 0){
												$upd_query  = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = '.$pick_id;
												$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
												$get_cell_value = $pick_id;
											}else
											if($pick_status === 1){
												$get_cell_value = $pick_id;
											}
										}
									}
								}

								if(!$sts){
									$err_column_array['error']["$excel_line_value$row"] = "Mobile Number length should be 10";
								}
								else
								if(!$mobile_sts){
									$err_column_array['error']["$excel_line_value$row"]  = "Invalid Mobile Number";
								}
								else
								if(!$email_sts){
									$err_column_array['error']["$excel_line_value$row"] = "Invalid Email";
								}

								// COMMON EMPLOYEE CODE CHECK
								if($excel_line_column_name === "employee_code"){
									$employee_code    = trim($get_cell_value);
									// EMPLOYEE EXITS CHECK
									if(!array_key_exists($employee_code,$employee_device_map)){
										$err_column_array['error']["$excel_line_value$row"] = "Employee Code '$employee_code' not exists";
									}
								}else 
								if($excel_line_column_name === "effective_from"){
									$effective_date    = $get_cell_value;
								}

								// ================== SHIFT CONFIG IMPORT ======================
							 	if($module_id === "shift_config"){
									
									if($excel_line_column_name === "applicable_shift"){
										$applicable_shifts = $get_cell_value;
									}else
									if($excel_line_column_name === "default_shift"){
										$default_shifts    = $get_cell_value;
										// DEFAULT SHIFT MUST EXIST IN APPLICABLE SHIFT
										$applicable_array  = array_map('trim', explode(',', $applicable_shifts));
										if(!in_array(trim($default_shifts), $applicable_array)){
											$err_column_array['error']["$excel_line_value$row"] = "Default Shift  must exist in Applicable Shift ";
										}
									}else
									if($excel_line_column_name === "shift_type"){
										$shift_type   =   $get_cell_value;  
									}
								}

								// ================== WEEKOFF CONFIG IMPORT ======================
								if($module_id === "weekoff_config"){
									if($excel_line_column_name === "week_off_type"){
										$week_off_type         =   $get_cell_value;  
									}else
									if($excel_line_column_name   === "applicable_week_off"){
										$applicable_week_off   =   $get_cell_value;
									}
								}

							}else{
								$err_column_array['error']["$excel_line_value$row"]   = "Empty values not be allowed";
							}
						}

						// TEMP DATA STORED
						if($module_id === "shift_config"){
							$temp_insert_data[] = [
								'employee_code'    => $employee_code,
								'device_code'      => $employee_device_map[$employee_code],
								'applicable_shift' => $applicable_shifts,
								'default_shift'    => $default_shifts,
								'shift_type'       => $shift_type,
								'effective_from'   => $effective_date
							];
						}else
						if($module_id === "weekoff_config"){
							$temp_insert_data[] = [
								'employee_code'       => $employee_code,
								'week_off_type'       => $week_off_type,
								'applicable_week_off' => $applicable_week_off,
								'effective_from'      => $effective_date
							];
						}
					}
					
					$err_column_count = count($err_column_array['error'] ?? []);
					if((int)$err_column_count > 0){
						$table_info = $this->get_excel_error_ui($err_column_array);
						return json_encode(array('success'=>false,'message'=>"File Has Error",'table_info'=>$table_info));
					}
					// CALL THE FUNCTION BASED ON MODULE ID
					if($module_id === "shift_config"){
						$this->config_data_entries($module_id,$temp_insert_data);
					}else 
					if($module_id === "weekoff_config"){
						$this->config_data_entries($module_id,$temp_insert_data);
					}	
		
				}
				return json_encode(array('success'=>true,'message'=>"Successfully file imported",'table_info'=>""));
			}
	    }
	}
	// SHIFT CONFIG & WEEKOFF CONFIG DATA ENTRIES
	public function config_data_entries($module_id,$temp_insert_data){
		if($module_id === "shift_config"){
			// TEMP TABLE CREATE
			$this->db->query("DROP TEMPORARY TABLE IF EXISTS cw_tmp_shift_config_import");
			$this->db->query("CREATE TEMPORARY TABLE cw_tmp_shift_config_import (employee_code VARCHAR(100) COLLATE utf8mb4_unicode_ci,device_code VARCHAR(50)  COLLATE utf8mb4_unicode_ci,applicable_shift VARCHAR(100) COLLATE utf8mb4_unicode_ci,default_shift VARCHAR(100) COLLATE utf8mb4_unicode_ci,shift_type         VARCHAR(100) COLLATE utf8mb4_unicode_ci,effective_from  DATE,end_date DATE DEFAULT '2099-12-31')ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
			$this->db->insert_batch('cw_tmp_shift_config_import', $temp_insert_data);
			
			// UPDATE PREVIOUS RECORD
			$close_prev_qry  = "UPDATE cw_shift_config c JOIN cw_tmp_shift_config_import t ON c.device_code = t.device_code SET c.end_date = DATE_SUB(t.effective_from, INTERVAL 1 DAY), c.trans_updated_by = '".$this->logged_id."',c.trans_updated_date = NOW() WHERE c.trans_status = 1 AND c.end_date = '2099-12-31' AND c.effective_from < t.effective_from";
			$this->db->query($close_prev_qry);

			// UPDATE SAME RECORD
			$upd_query    = "UPDATE cw_shift_config c JOIN cw_tmp_shift_config_import t ON c.device_code = t.device_code AND c.effective_from = t.effective_from SET c.applicable_shift = t.applicable_shift, c.default_shift    = t.default_shift, c.shift_type = t.shift_type, c.trans_updated_by = '".$this->logged_id."', c.trans_updated_date = NOW(),c.trans_status = 1";
			$this->db->query($upd_query);

			// INSERT NEW RECORD
			$prime_query       = "INSERT INTO cw_shift_config(employee_code,device_code,applicable_shift,default_shift,shift_type,effective_from,end_date,trans_created_by,trans_created_date,trans_status)
			SELECT t.employee_code,t.device_code,t.applicable_shift,t.default_shift,t.shift_type,t.effective_from,'2099-12-31','".$this->logged_id."',NOW(),1 FROM cw_tmp_shift_config_import t LEFT JOIN cw_shift_config c ON c.device_code = t.device_code AND c.effective_from = t.effective_from WHERE c.prime_shift_config_id IS NULL";
			$this->db->query($prime_query);
		}else{

			$this->db->query("DROP TEMPORARY TABLE IF EXISTS cw_tmp_weekoff_config_import");
			$this->db->query("CREATE TEMPORARY TABLE cw_tmp_weekoff_config_import (employee_code VARCHAR(100) COLLATE utf8mb4_0900_ai_ci,week_off_type VARCHAR(100) COLLATE utf8mb4_0900_ai_ci,applicable_week_off  VARCHAR(100) COLLATE utf8mb4_0900_ai_ci,effective_from DATE,end_date DATE DEFAULT '2099-12-31') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci");

			$this->db->insert_batch('cw_tmp_weekoff_config_import', $temp_insert_data);

			$close_prev_qry  = "UPDATE cw_weekoff_config c JOIN cw_tmp_weekoff_config_import t ON c.employee_code = t.employee_code SET c.end_date = DATE_SUB(t.effective_from, INTERVAL 1 DAY), c.trans_updated_by = '".$this->logged_id."',c.trans_updated_date = NOW() WHERE c.trans_status = 1 AND c.end_date = '2099-12-31' AND c.effective_from < t.effective_from";
			$this->db->query($close_prev_qry);
			
			$upd_query = "UPDATE cw_weekoff_config c JOIN cw_tmp_weekoff_config_import t ON c.employee_code = t.employee_code AND c.effective_from = t.effective_from SET c.week_off_type = t.week_off_type,c.applicable_week_off = t.applicable_week_off,c.trans_updated_by = '".$this->logged_id."',c.trans_updated_date  = NOW(),c.trans_status = 1";
			$this->db->query($upd_query);

			$insert_query = "INSERT INTO cw_weekoff_config (employee_code,week_off_type,applicable_week_off,
			effective_from,end_date,trans_created_by,trans_created_date,trans_status) SELECT t.employee_code,t.week_off_type,
			t.applicable_week_off,t.effective_from,'2099-12-31','".$this->logged_id."',NOW(),1 FROM cw_tmp_weekoff_config_import t LEFT JOIN cw_weekoff_config c ON c.employee_code = t.employee_code AND c.effective_from = t.effective_from WHERE c.prime_weekoff_config_id IS NULL";
			$this->db->query($insert_query);

		}
	}

	//FOR MANUFACTURING UNIT
	public function shift_mapping($employee_code){
		$qry = "";
		if($employee_code){
			$qry = ' and cw_shift_config.employee_code = "'.$employee_code.'"';
		}
		$shift_config_qry  = 'select employee_code,applicable_shift,shift_type,effective_from from cw_shift_config where trans_status = 1 and shift_type = "M" '.$qry;
		$shift_config_info = $this->db->query("CALL sp_a_run ('RUN','$shift_config_qry')");
		$shift_config_rslt = $shift_config_info->result_array();
		$shift_config_info->next_result();

		$shift_config_arr = [];
		foreach ($shift_config_rslt as $shift_key => $shift_val) {
			$shift_config_arr[$shift_val['employee_code']] = $shift_val;
		}
		return $shift_config_arr;
	}

	// GET START DATE END DATE PREVIOUS MONTH
	function get_start_end_date($salary_start, $salary_end){
		// START DATE // IF FIRST DAY OF MONTH ->PREVIOUS MONTH FIRST DAY // OTHER WISE SUBTRACT 1 MONTH NORMALLY
		$start      = new DateTime($salary_start);
		if($start->format('d') == '01'){	
			$start->modify('first day of last month');
		}else{
			$start->modify('-1 month');
		}
		$start_date = $start->format('Y-m-d');
 
		// END DATE //IF LAST DAY OF MONTH -> PREVIOUS MONTH LAST DAY // OTHERWISE ->SUBTRACT 1 MONTH NORMALLY 
		$end        = new DateTime($salary_end);
		if($end->format('d') == $end->format('t')){
			$end->modify('last day of last month');
		}else{
			$end->modify('-1 month');
		}
		$end_date  = $end->format('Y-m-d');

		return ['start_date' => $start_date,'end_date'   => $end_date];
	}

	// GET EMPLOYEE DATA BASED ON EMPLOYEE CODE
	public function get_employee_data($logged_emp_code,$prime_id){
		$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 = 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;
		$col_name            = $component_result[0]->label_name;
		$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];
		
		$emp_det_qry         = "SELECT e.employee_code,e.emp_name,e.date_of_joining,d.department AS department_name,apt.approval_type,CONCAT(fl.employee_code,' - ',fl.emp_name) AS first_level_approval_name,CONCAT(sl.employee_code,' - ',sl.emp_name) AS second_level_approval_name,pt.$pick_list_val_2 AS component_value FROM cw_employees e LEFT JOIN cw_department d ON d.prime_department_id = e.department LEFT JOIN cw_approval_type apt ON apt.prime_approval_type_id = e.approve_type LEFT JOIN cw_employees fl ON fl.employee_code = e.first_level_approval LEFT JOIN cw_employees sl ON sl.employee_code = e.second_level_approval LEFT JOIN $pick_table pt  ON pt.$pick_list_val_1 = e.$col_name WHERE e.termination_status = 0 AND e.employee_code = '$logged_emp_code'";
		$emp_det_info        = $this->db->query($emp_det_qry);
		$emp_det_result      = $emp_det_info->result();
		$emp_det_info->next_result();

		$past_att_qry    = "SELECT ls.leave_status AS leave_status FROM cw_past_attendance_request par LEFT JOIN cw_leave_status ls ON ls.prime_leave_status_id = par.leave_status WHERE par.trans_status = 1  AND par.prime_past_attendance_request_id = '$prime_id'";
		$past_att_data   = $this->db->query($past_att_qry);
		$past_att_result = $past_att_data->result();
		$past_att_data->next_result();

		$leave_status    = (!empty($past_att_result) && !empty($past_att_result[0]->leave_status)) ? $past_att_result[0]->leave_status : "Pending";

		$emp_det_str     = "<tr>
								<td style = 'text-align:center;' >".$emp_det_result[0]->employee_code."</td>
								<td style = 'text-align:center;' >".$emp_det_result[0]->emp_name."</td>
								<td style = 'text-align:center;' >".$emp_det_result[0]->date_of_joining."</td>
								<td style = 'text-align:center;' >".$emp_det_result[0]->department_name."</td>
								<td style = 'text-align:center;' >".$emp_det_result[0]->component_value."</td>
								<td style = 'text-align:center;' >".$emp_det_result[0]->approval_type."</td>
								<td style = 'text-align:center;' >".$emp_det_result[0]->first_level_approval_name."</td>
								<td style = 'text-align:center;' >".$emp_det_result[0]->second_level_approval_name."</td>
								<td style = 'text-align:center;' >".$leave_status."</td>
							</tr>";
		return $emp_det_str;
	}
	// RETRO ENTRY FUNCTION
	public function retro_entry($post_data,$skey){
		$employee_code        = $post_data['employee_code'];
		$request_type         = $post_data['request_type'];
		$permission_date      = $post_data['permission_date'];
		$shift_date           = $post_data['shift_date'];
		$from_date            = $post_data['from_date'];
		$to_date              = $post_data['to_date'];
		$from_date_type       = $post_data['from_date_type'];
		$to_date_type         = $post_data['to_date_type'];
		$day_type             = $post_data['day_type'];
		$procss_dates         = [];
		$shift_date_arr       = array("4","6","7");
		$date_type            = 1;
		$apr_whole_day_status = [1=>"L",3=>"O",8=>"O",7=>"P"];
		$approve_status       = isset($apr_whole_day_status[$request_type]) ? $apr_whole_day_status[$request_type] : "P";

		if(in_array($request_type, $shift_date_arr)){
			if($request_type === "4" || $request_type === "5"){
				if($permission_date){
					$procss_dates[]  = date('Y-m-d', strtotime($permission_date));
				}
			}else{
				if($shift_date){
					$procss_dates[]  = date('Y-m-d', strtotime($shift_date));
				}
			}
		}else{
			 $procss_dates[]         = date('Y-m-d', strtotime($from_date)); // ALREADY FLAT ARRAY 
		}

		
		foreach($procss_dates as $att_date){
			if(!$att_date){
				continue;
			}
			$att_date = date('Y-m-d', strtotime($att_date));
			// DATE TYPE WILL PROCESS
			if($day_type){
				$date_type     = (int)$day_type;
			}else{
				if($att_date == $from_date){
					$date_type = (int)$from_date_type;
				}else
				if($att_date == $to_date){
					$date_type = (int)$to_date_type;
				}else{
					$date_type = 1;
				}
			}

			//GET CURRENT HALF -DAY STATUSES /COUNTS FROM TIME ENTRY 
			$time_qry = 'SELECT first_half_status,first_half_count,second_half_status,second_half_count FROM cw_time_entry
			WHERE employee_code = "'.$employee_code.'" AND att_date = "'.$att_date.'" AND trans_status  = 1 LIMIT 1';
			$time_rs  = $this->db->query($time_qry)->row();

			if(!$time_rs){
				continue;
			}

			// CHECK IF RETRO ENTRY ALREADY EXISTS 
			$retro_qry = $this->db->query('SELECT first_half_status,second_half_status FROM cw_retro_entry WHERE employee_code="'.$employee_code.'" AND att_date="'.$att_date.'" LIMIT 1');
			if($retro_qry->num_rows()>0){
				$retro              = $retro_qry->row();
				$first_half_status  = $retro->first_half_status;
				$second_half_status = $retro->second_half_status;
			}else{
				$first_half_status  = $time_rs->first_half_status;
				$second_half_status = $time_rs->second_half_status;
			}

			if($skey == "cancelapprove"){
				if($date_type == 1){
					$first_half_status  = $time_rs->first_half_status;
					$second_half_status = $time_rs->second_half_status;
				}else
				if($date_type == 2){
					$first_half_status  = $time_rs->first_half_status;
				}else
				if($date_type == 3){
					$second_half_status = $time_rs->second_half_status;
				}
			}else{
				$status_value = ($skey == "past_request") ? "APLY" : $approve_status;
				if($date_type == 1){
					$first_half_status  = $status_value;
					$second_half_status = $status_value;
				}else
				if($date_type == 2){
					$first_half_status  = $status_value;
				}else
				if($date_type == 3){
					$second_half_status = $status_value;
				}
			}

			if($first_half_status === $second_half_status){
				$whole_day_status       = $first_half_status;
			}else{      
				$whole_day_status       = $first_half_status.$second_half_status;
			}      

			if($retro_qry->num_rows() == 0){
				$ins_qry = 'INSERT INTO cw_retro_entry(employee_code,att_date,first_half_status,second_half_status,whole_day_status,trans_status) VALUES ("'.$employee_code.'","'.$att_date.'","'.$first_half_status.'","'.$second_half_status.'","'.$whole_day_status.'","1")';
				$this->db->query($ins_qry);

			}else{
				$upd_qry = 'UPDATE cw_retro_entry SET first_half_status="'.$first_half_status.'",second_half_status="'.$second_half_status.'",whole_day_status="'.$whole_day_status.'" WHERE employee_code="'.$employee_code.'" AND att_date="'.$att_date.'"';
				$this->db->query($upd_qry);
			}
		}
	}
	// IMPORT COFF MOFF UPDATE PROCESS
	public function import_coff_moff_update($employee_code,$leave_date,$leave_count,$leave_type){
		$created_on = date("Y-m-d H:i:s");
		/* GET CONFIG */
		$qry  = 'SELECT coff,leave_category FROM cw_leave_creation WHERE trans_status=1 AND prime_leave_creation_id="'.$leave_type.'"';
		$info = $this->db->query("CALL sp_a_run ('SELECT','$qry')");
		$res  = $info->result();
		$info->next_result();
		$coff           = (int)$res[0]->coff;
		$leave_category = (int)$res[0]->leave_category;
		/* ================= COFF ================= */
		if($coff === 1){
			$remaining = $leave_count;
			$qry       = 'SELECT prime_coff_entry_id,balance_count FROM cw_coff_entry WHERE employee_code="'.$employee_code.'" AND credited_date <= "'.$leave_date.'" AND balance_count > 0 AND trans_status=1 ORDER BY credited_date ASC';
			$info = $this->db->query("CALL sp_a_run ('SELECT','$qry')");
			$res  = $info->result();
			$info->next_result();

			foreach($res as $row){
				if($remaining <= 0) break;
				$deduct      = min($remaining,$row->balance_count);
				$new_balance = $row->balance_count - $deduct;
				/* STATUS */
				if($new_balance == 0){
					$status = 2; // Taken
				}else{
					$status = 5; // Partial
				}
				$upd        = 'UPDATE cw_coff_entry SET balance_count="'.$new_balance.'",coff_status="'.$status.'",
				trans_updated_by="'.$this->logged_id.'",trans_updated_date="'.$created_on.'" WHERE prime_coff_entry_id="'.$row->prime_coff_entry_id.'"';
				$this->db->query("CALL sp_a_run ('UPDATE','$upd')");
				$remaining -= $deduct;
			}
		}

		/* ================= MOFF ================= */
		if($leave_category === 11){
			$remaining = $leave_count;
			$qry = 'SELECT prime_moff_entry_id,bal_days FROM cw_moff_entry WHERE employee_code="'.$employee_code.'" 
			AND "'.$leave_date.'" >= cr_date AND "'.$leave_date.'" <= end_date AND bal_days > 0 AND trans_status=1 
		    ORDER BY cr_date ASC';
			$info = $this->db->query("CALL sp_a_run ('SELECT','$qry')");
			$res  = $info->result();
			$info->next_result();

			foreach($res as $row){
				if($remaining <= 0) break;
				$deduct      = min($remaining,$row->bal_days);
				$new_balance = $row->bal_days - $deduct;
				$status      = ($new_balance == 0) ? 2 : 5;
				$upd         = 'UPDATE cw_moff_entry SET bal_days="'.$new_balance.'",moff_status="'.$status.'",
				trans_updated_by="'.$this->logged_id.'",trans_updated_date="'.$created_on.'"
				WHERE prime_moff_entry_id="'.$row->prime_moff_entry_id.'"';
				$this->db->query("CALL sp_a_run ('UPDATE','$upd')");
				$remaining  -= $deduct;
			}
		}
	}
	// BULK TO FOR LOOP TO UPDATE
	public function bulk_coff_moff_update($data){
		$created_on = date("Y-m-d H:i:s");
		/* GROUP DATA */
		$grouped    = [];
		foreach($data as $row){
			$key = $row['employee_code'].'|'.$row['leave_type'].'|'.$row['leave_date'];
			if(!isset($grouped[$key])){
				$grouped[$key] = $row;
			}else{
				$grouped[$key]['leave_count'] += $row['leave_count'];
			}
		}

		/* PROCESS GROUPED DATA */
		foreach($grouped as $row){
			$employee_code = $row['employee_code'];
			$leave_date    = $row['leave_date'];
			$leave_count   = $row['leave_count'];
			$leave_type    = $row['leave_type'];
			$this->import_coff_moff_update($employee_code,$leave_date,$leave_count,$leave_type);
		}
	}
}
?>