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/uds.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");
require('./application/libraries/dompdf/autoload.inc.php');
require('./application/libraries/PHPSpreadsheet/autoload.php');
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
ini_set("memory_limit","5000M");	
ini_set("max_execution_time","-1");
use Dompdf\Dompdf;
use DOMDocument;
use ZipArchive;
use RarArchive;
#[\AllowDynamicProperties]
abstract class Action_controller extends Secure_Controller{
	public $control_name;
	public $logged_id;
	public $logged_role;
	public $logged_user_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 $export_pick_arr       = array();
	public $form_arr              = array();
	public $comp_info             = array();
	public $control_whr_cond;
	public $join_qry_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","monthly_input_fms"=>"employees","time_sheet"=>"employees","pay_structure"=>"employees","process_payroll_fms"=>"employees","employee_onboard"=>"employees","process_payroll_man"=>"employees","pay_structure_report"=>"employees","pre_audit_report"=>"employees",);
	// "misc_payment"=>"employees",
	public $formula_allow    = array("employees"=>true,);
	
	public $mi_base          = array("monthly_input"=>"monthly_input","monthly_input_fms"=>"monthly_input_fms","time_sheet"=>"time_sheet","misc_input_fms"=>"misc_input_fms","pre_audit_report"=>"employees",);
	// 
	public $payroll_base     = array("process_payroll"=>"process_payroll","process_payroll_fms"=>"process_payroll_fms","process_payroll_man"=>"process_payroll_man",);

	public function __construct($module_id = NULL){
		parent::__construct($module_id);
		$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_user_name   = $this->session->userdata('logged_user_name');

		// $query = $this->db->get_where('logged_user_info', array('user_id' =>$this->logged_user_name, 'user_status' => 1), 1);
		// if($query->num_rows() == 1){
		// 	if($query->row()->ip_address !== $_SERVER['REMOTE_ADDR']){ 
		// 		redirect('home');				
		// 		// echo '<script>window.location.reload();</script>';
		// 		exit(0);
		// 	}		
		// }
		//DR CODE FOR DYNAMIC SELECT QRY ADD 
		$this->prime_id           = "prime_".$this->control_name."_id";
		$this->prime_table        = $this->db->dbprefix($this->control_name);

		if($this->prime_table === 'cw_employee_onboard'){
			$this->base_query         = "select @SELECT@ from cw_employees";
			$this->select_query       = "cw_employees.prime_employees_id,";
			$this->prime_table        = "cw_employees";
			$this->prime_id           = "prime_employees_id";
		}elseif($this->prime_table === 'cw_pre_audit_report'){
			$this->prime_table        = "cw_pre_audit_salary";
			$this->prime_id           = "prime_pre_audit_salary_id";

			$this->base_query         = "select @SELECT@ from $this->prime_table";
			$this->select_query       = "$this->prime_table.$this->prime_id,";
		}
		else{
			$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');
			require('./phpmailer/class.phpmailer.php');
		}
		
		
	}	
	/******************** 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'];
			}
		}
		//mysqli_close($this->db_conn_id);
		return json_decode(json_encode(array("sts"=>$sts,"msg"=>$msg,"rslt"=>$final_rslt)));			
    }
	
	public function page_info(){
		$this->control_whr_cond  = ' and field_show = "1" '; 
		$this->join_qry_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]){
				// if($this->control_name === 'misc_payment'){
				// 	$this->control_whr_cond  = ' and misc_check = "1"'; 
				// }else{
					$this->control_whr_cond  = ' and (earn_month_check = "1" OR deduction_month_check = "1")'; 
					
					$order_by               = ' ORDER BY monthly_input_sort asc';
				// }
			}else
			if($this->payroll_base[$this->control_name]){
				$this->control_whr_cond  = ' and (earn_payroll_check = "1" OR ded_payroll_check = "1")'; 
				
				$order_by                = ' ORDER BY payroll_sort asc'; 
			}
		}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)';
			$this->join_qry_cond    = ' inner join cw_form_setting on cw_form_setting.input_for = cw_form_view_setting.prime_form_view_id';
			$order_by               = ' ORDER BY onboard_order asc';
		}
		// else
		// if($this->mi_base[$this->control_name]){//FOR MONTHLY INPUT
		// }else
		// if($this->payroll_base[$this->control_name]){
		// }	
		//echo '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; die;
		// UDY TEMP NNED TO REMOVE		
		$pro_qry   = [];
		$pro_qry[] = array("return"=>"quicklink","qry"=>'select quicklink from cw_modules where module_id = "'.$this->control_name.'"');
		$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);
		$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 pick_query_for = "'.$this->logged_user_role.'" 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"');
		$pro_qry[]   = array("return"=>"company_info","qry"=>'select * from cw_company_information where cw_company_information.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;	
					$label_name  = $value->label_name;	

					//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)){
							if($label_name === "position" || $label_name ==="personal_code"){
								$pro_pick_list[$key]  = $value;
							}
						}
					}else
					if($this->payroll_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;
							}
						}
					}
				}
				//print_r($pro_pick_list); die;
				$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;
				if(!$this->mi_base[$this->control_name]){
					if($this->table_head[1000]->label_name){
						$this->table_head[1000]->label_name = 'trans_created_date'; 
					}
					if($this->table_head[1000]->view_name){
						$this->table_head[1000]->view_name  = 'Created On'; 
					}
					if($this->table_head[1000]->field_type){
						$this->table_head[1000]->field_type = 13;
					}
				}
				$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;
				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 cats_page_info(){
		$this->control_whr_cond  = ' and field_show = "1" '; 
		$this->join_qry_cond     = "";	
		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")'; 
					
					$order_by               = ' ORDER BY monthly_input_sort asc';
			}else
			if($this->payroll_base[$this->control_name]){
				$this->control_whr_cond  = ' and (earn_payroll_check = "1" OR ded_payroll_check = "1")'; 
				
				$order_by                = ' ORDER BY payroll_sort asc'; 
			}
		}else{
			$control_name    = $this->control_name;
			$order_by        = ' ORDER BY input_for,field_sort asc';
		}	
		
		// UDY TEMP NNED TO REMOVE		
		$pro_qry   = [];		
		$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);
		$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"');
		$pro_qry[]   = array("return"=>"company_info","qry"=>'select * from cw_company_information where cw_company_information.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{
				$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;	
					$label_name  = $value->label_name;	

					//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)){
							if($label_name === "position" || $label_name ==="personal_code"){
								$pro_pick_list[$key]  = $value;
							}
						}
					}else
					if($this->payroll_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;
							}
						}
					}
				}
				//print_r($pro_pick_list); die;
				$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;
				if(!$this->mi_base[$this->control_name]){
					$this->table_head[1000]->label_name = 'trans_created_date'; 
					$this->table_head[1000]->view_name  = 'Created On'; 
					$this->table_head[1000]->field_type = 13;
				}
				$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;
				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  = ' and field_show = "1" '; 
		$this->join_qry_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]){
				// if($this->control_name === 'misc_payment'){
				// 	$this->control_whr_cond  = ' and misc_check = "1"'; 
				// }else{
					$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)';
			$this->join_qry_cond    = ' inner join cw_form_setting on cw_form_setting.input_for = cw_form_view_setting.prime_form_view_id';
			$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   = [];
		$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);
		
		$pro_qry[] = array("return"=>"role_condition_list","qry"=>'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"');

		$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"');

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

				$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);
					}
				}
				$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;
				if($this->control_name !== "loan"){
					if(!$this->mi_base[$this->control_name]){
						$this->table_head[1000]['label_name'] = 'trans_created_date'; 
						$this->table_head[1000]['view_name']  = 'Created Date'; 
						$this->table_head[1000]['field_type'] = 13; 
					}
				}
				
				$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 //DON'T DELETE
						if($this->mi_base[$this->control_name]){
							$this->get_import_pick_list_qry($pro_pick_list);
						}
					}
				}
			}	
		}
	}

	public function view_info($prime_id){
		if($this->alias_control[$this->control_name]){
			$control_name = $this->alias_control[$this->control_name];
		}else{
			$control_name = $this->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)';
			$this->join_qry_cond    = ' inner join cw_form_setting on cw_form_setting.input_for = cw_form_view_setting.prime_form_view_id';
			$order_by = ' ORDER BY onboard_order asc';
		}	

		$pro_qry     = [];
		if($this->control_name === "employee_log_report"){
			$control_name   = "employees";
		}
		$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);

		$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');

		$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 = "'.$control_name.'" and pick_query_for = "'.$this->logged_user_role.'" 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) 
		$pro_qry[]   = array("return"=>"form_condition_list","qry"=>'select * from cw_form_condition_formula where cond_module_id = "'.$control_name.'" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_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) 	

		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){
					$prime_form_id    = (int)$value->prime_form_id;
					$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;

				//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   = [];
		$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) ORDER BY input_for,field_sort asc');
		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;
			}	
		}
	}

	//MISC PAYMENT(MISC INPUT FMS) INFO 22OCT22 START
	public function misc_payment_info(){
		$emp_inp_qry     = 'select * from cw_form_setting where prime_module_id in ("employees") and field_show = "1" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",user_right_for) and (earn_month_check = "1" OR deduction_month_check = "1") and label_name in ("employee_code","emp_name","wbs_element","position","activity_no","date_of_joining","date_of_birth") ORDER BY monthly_input_sort asc';
		// input_for,field_sort
		$emp_inp_data    = $this->db->query("CALL sp_a_run ('SELECT','$emp_inp_qry')");
		$emp_inp_rslt    = $emp_inp_data->result();
		$emp_inp_data->next_result();

		$un_select_cols  = '"employee_esi","employer_esi","employee_pf","employer_pf","eps","total_earnings","total_deductions","net_pay"';

		// and field_show = "1"
		$mi_inp_qry      = 'select * from cw_form_setting where prime_module_id in ("misc_input_fms") and table_show = "1" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",user_right_for) and label_name not in ('.$un_select_cols.') ORDER BY input_for,table_sort asc';
		$mi_inp_data     = $this->db->query("CALL sp_a_run ('SELECT','$mi_inp_qry')");
		$mi_inp_rslt     = $mi_inp_data->result();
		$mi_inp_data->next_result();

		//FOR MI FMS BASED PICKLIST AND AUTOCOMPLETE INPUTS GET
		$mi_pick_qry      = 'select * from cw_form_setting where prime_module_id in ("misc_input_fms") and field_type = "5" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",user_right_for)';
		$mi_pick_data     = $this->db->query("CALL sp_a_run ('SELECT','$mi_pick_qry')");
		$mi_pick_rslt     = $mi_pick_data->result();
		$mi_pick_data->next_result();
		
		$emp_arr_count   = count($emp_inp_rslt ?? []);
		$table_info      = [];
		$pro_pick_list   = [];

		//FOR EMLPLOYEE MODULE INPUT 
		foreach($emp_inp_rslt as $key => $value){
			$table_info[$key]   = $value;
			$pro_pick_list[$key]  = $value;
		}

		//FOR MISC INPUT FMS MODULE INPUT 
		$mi_inp_key_count   = $emp_arr_count; 
		foreach($mi_inp_rslt as $key => $mi_inp_val){
			//FOR MISC INPUT GET
			$table_info[$mi_inp_key_count]   = $mi_inp_val;
			$mi_inp_key_count++;
		}

		//FOR MISC INPUT FMS MODULE PICKLIST AND AUTOCOMPLETE MERGE TO EMPLOYEE MODUE PICKLIST ARRAY
		$pick_key_count   = $emp_arr_count; 
		foreach($mi_pick_rslt as $pick_val){
			//FOR MISC INPUT GET
			$pro_pick_list[$pick_key_count]   = $pick_val;
			$pick_key_count++;
		}

		//TABLE HEAD AND PICKLIST ARRAY CREATE
		$this->table_head           = $table_info;
		$this->get_pick_list_qry($pro_pick_list);
		//$this->get_import_pick_list_qry($pro_pick_list);
	}
	//MISC PAYMENT INFO 22OCT22 END

	public function get_pick_list_qry($pro_pick_list){
		//print_r($pro_pick_list); die;
		$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);
				}
			};
			//echo "BSK $pick_list :: $pick_table :: $field_isdefault <br/>";
			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 = "imp_".$pick_list_val_2;
						if($pick_display){
							$pick_list    = "$pick_list_val_1,CONCAT_WS(\" ~ \", $pick_display) as $pick_list_val_2,$pick_list_val_2 as $imp_pick_list_val_2";
							$pick_qry     = 'select '.$pick_list.' from '.$pick_table.' where trans_status = 1 '.$where_condition;
							if($pick_table === "cw_category"){
								$pick_qry = 'select '.$pick_list.' from '.$pick_table.' where trans_status = 1 and prime_category_id != 1 '.$where_condition;
							}else
							/* Only for UDS */
							$area_control_where   = '';
							if((int)$this->logged_user_role !== 1){
								if($pick_table === "cw_sap_personal_area"){
									$area_control_where   = 'and '.$pick_table.'.personal_code in ('.$this->logged_area_access.') ';
								}else{
									$area_control_where   = 'and cw_pay_structure.personal_code in ('.$this->logged_area_access.') ';
								}
							}
							if($pick_table === "cw_sap_personal_area"){	
								$pick_qry = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_table.'.trans_status = 1 '.$area_control_where.$where_condition;
							}else
							if($pick_table === "cw_sap_wbs"){
								$qry      = "wbs_element";
								if($label_id === 'network_id'){
									$qry  = "network_id";
								}
								$pick_qry = 'select '.$pick_list.' from '.$pick_table.' inner join cw_pay_structure on cw_pay_structure.'.$qry.' = '.$pick_table.'.'.$pick_list_val_1.' where '.$pick_table.'.trans_status = 1 '.$area_control_where.$where_condition;
							}else
							if($pick_table === "cw_sap_activity"){
								$pick_qry = 'select '.$pick_list.' from '.$pick_table.' inner join cw_pay_structure on cw_pay_structure.activity_no = '.$pick_table.'.'.$pick_list_val_1.' where '.$pick_table.'.trans_status = 1 '.$area_control_where.$where_condition;
							}else
							if($pick_table === "cw_sap_position"){
								//$pick_list    = "$pick_list_val_1,CONCAT_WS(\" ~ \", $pick_display,cw_pay_structure.gross) as $pick_list_val_2,$pick_list_val_2 as $imp_pick_list_val_2";
								$pick_qry = 'select '.$pick_list.' from '.$pick_table.' inner join cw_pay_structure on cw_pay_structure.position = '.$pick_table.'.'.$pick_list_val_1.' where '.$pick_table.'.trans_status = 1 '.$area_control_where.$where_condition;
							}else{
								$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,'imp_pick_list_val_2' => $imp_pick_list_val_2,'table_show' => $table_show,'search_show' => $search_show,'field_isdefault' => $field_isdefault,'pick_list_import' => $pick_list_import,));
						}
					}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,'imp_pick_list_val_2' => $imp_pick_list_val_2,'table_show' => $table_show,'search_show' => $search_show,'field_isdefault' => $field_isdefault,'pick_list_import' => $pick_list_import,));
					}
				}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,'pick_list_import' => $pick_list_import,));
				}
			}
		}

		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'];
						$pick_list_import = (int)$pro_info['pick_list_import'];

						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'];
							$imp_pick_list_val_2 = $pro_info['imp_pick_list_val_2'];
							// if($pick_list_type === 1){
							if($pick_list_import === 2){
								$imp_pick_key   = array_column($list_info ?? [], $pick_list_val_2);
								$imp_pick_val   = array_column($list_info ?? [], $pick_list_val_2);								
							}else{
								$imp_pick_key   = array_column($list_info ?? [], $pick_list_val_1);
								$imp_pick_val   = array_column($list_info ?? [], $pick_list_val_2);
							}		
							$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 ?? []);
							$import_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'];

							$imp_pick_key  = array_column($list_info ?? [], "auto_list_pick");
							$imp_pick_val  = array_column($list_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 ?? []);
							$import_pick   = array_combine( $imp_pick_key ?? [], $imp_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);
						$this->export_pick_arr[$label_id]   = $import_pick;
					}
				}
			}
		}
	}

	//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);
				}
			};

			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)

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

							//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'];
							//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;
					}
				}
			}
		}
	}
	//DHR CODE END FOR TIME SHEET(MI FMS) EXPORT A DATA AND THEN SAME AS USING IMPORT  
	
	//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_input         = "";
			$on_change_input       = "";
			$on_blur_input         = "";
			
			foreach($condition_check_form as $label_name){
				$cond_from_qry  = '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_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'];

						/*============ 
							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;
							$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;
								$field_type  = $this->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 *************************/	
	//PROVIDE BASE DATA FOR MODULE
	/*public function collect_base_info(){
		$this->control_name      = strtolower($this->router->fetch_class());
		$this->control_whr_cond  = ""; 
		$this->join_qry_cond     = "";
		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)';
			$this->join_qry_cond    = ' inner join cw_form_setting on cw_form_setting.input_for = cw_form_view_setting.prime_form_view_id';
		}
		$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->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();
		if($this->control_name === 'request' || $this->control_name === 'direct_leave_entry' || $this->control_name === 'approval'){
		$this->get_emp_data();
		}				
	}*/
	
	//PROVIDE BASE DATA FOR MODULE
	/*public function collect_custom_info(){
		$this->control_name      = strtolower($this->router->fetch_class());
		$this->control_whr_cond  = ""; 
		$this->join_qry_cond     = "";
		$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->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,";
		// $this->get_quick_link();
		// $this->get_table_head();		
		$this->get_view_info();
		$this->get_form_info();
		$this->get_role_condition();
		$this->get_query_and_drop();
		// $this->get_condition();
		$this->role_based_condition();			
	}*/
	/* ==============================================================*/
	/* =================== BASE FUNCTIONS - START ===================*/
	/* ==============================================================*/
	// //FUNCTION FOR GET A EMPLOYEE PICKLIST LABEL NAMES FROM FORM SETTING TABLE
	public function get_emp_data(){
		//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;
		$employee_code = $this->session->userdata('logged_emp_code');		
		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_picklist_arr    = array_reduce($emp_pick_rlst ?? [], function($result, $arr){			
	    	$result[$arr['employee_code']] = $arr;
	    	return $result;
		}, array());
		$this->emp_pick_arr = $emp_picklist_arr;	
	}
	// PROVIDE QUICK LINK LIST VIEW
	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();
		$this->general_setting_info = $general_set_rslt;
	}
	// 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)'.$this->control_whr_cond.' ';		
		$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(){
		//FOR ONBOARD
		if($this->control_whr_cond){
			$order_by = ' ORDER BY onboard_order asc';
		}else{
			$order_by = ' ORDER BY cw_form_view_setting.form_view_sort asc';
		}
		$view_query = 'select DISTINCT cw_form_view_setting.* from cw_form_view_setting'.$this->join_qry_cond.' where prime_view_module_id = "'.$this->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)'.$this->control_whr_cond.$order_by;
		$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 === 'monthly_input_fms' || $this->control_name === 'time_sheet' || $this->control_name === 'pay_structure' || $this->control_name === 'process_payroll_fms' || $this->control_name === 'misc_input_fms'){
			$control_name = 'employees';
		}else{
			$control_name = $this->control_name;
		}
		//FOR ONBOARD
		if($this->control_whr_cond){
			$order_by = ' ORDER BY onboard_order asc';
		}else{
			$order_by = ' ORDER BY input_for,field_sort asc';
		}
		$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)'.$this->control_whr_cond.$order_by;
		// echo "from_query::$from_query";
		$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;

		//Prime id based array
		//$form_arr = (array) $form_result;
		$form_arr = json_decode(json_encode($form_result), true);
		$this->form_arr   = array_reduce($form_arr ?? [], function ($result, $arr) {		
		    $result[$arr['prime_form_id']] = $arr;
		    return $result;
		}, array());
	}
	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;		
	}
	// 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();
		$this->leave_financial_info = $fin_result;				
	}
	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());
		$this->category_month_day = $cat_month_day_arr;				
	}
	// 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);
					}
			}
			$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){
		$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 = "'.$this->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 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;
	}
	//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;
			$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();
			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];
						$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";
						}
						
						if($pick_table === "cw_category"){
							$pick_query = "select $pick_list from $pick_table where trans_status = 1 and prime_category_id != 1 $where_condition";
						}else
						/* Only for UDS */
						if($pick_table === "cw_sap_personal_area"){							
							$pick_query = "select $pick_list from $pick_table where $pick_table.personal_code in (".$this->logged_area_access.") $where_condition";
						}else
						if($pick_table === "cw_sap_wbs"){
							$qry = "wbs_element";
							if($label_id === 'network_id'){
								$qry = "network_id";
							}
							$pick_query = "select $pick_list from $pick_table inner join cw_pay_structure on cw_pay_structure.$qry = $pick_table.$pick_list_val_1 where $pick_table.trans_status = 1 and cw_pay_structure.personal_code in (".$this->logged_area_access.") $where_condition";
						}else
						if($pick_table === "cw_sap_activity"){
							$pick_query = "select $pick_list from $pick_table inner join cw_pay_structure on cw_pay_structure.activity_no = $pick_table.$pick_list_val_1 where $pick_table.trans_status = 1 and cw_pay_structure.personal_code in (".$this->logged_area_access.") $where_condition";
						}else
						if($pick_table === "cw_sap_position"){
							$pick_query = "select $pick_list from $pick_table inner join cw_pay_structure on cw_pay_structure.position = $pick_table.$pick_list_val_1 where $pick_table.trans_status = 1 and cw_pay_structure.personal_code in (".$this->logged_area_access.") $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;
						//IMPORT FUNCTION FOR MONTHLY INPUT FMS MODULE TO EXPORT A PICKLIST DATA(FOR USER IMPORT THAT EXPORTED DATA IN TIME SHEET MODULE)
						$imp_pick_list     = ""; 
						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";
						}
						if($imp_pick_list){
							$pick_imp_qry    = "select $imp_pick_list from $pick_table where trans_status = 1";
							$pick_imp_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_imp_qry')");
							$pick_imp_rslt   = $pick_imp_data->result();
							$pick_imp_data->next_result();

							// if($label_name === "role"){
							// 	$label_name  = "category";
							// }
							$pick_imp_key        = array_column($pick_imp_rslt ?? [], $imp_pick_list_val_2);
							$pick_imp_val        = array_column($pick_imp_rslt ?? [], $imp_pick_list_val_1);
							// if($pick_list_import === 1){
							// 	$pick_imp_key    = array_column($pick_result, $pick_list_val_2);
							// 	$pick_imp_val    = array_column($pick_result, $pick_list_val_1);
							// }
							//CODE START FOR TIME SHEET TABLE DATA EXPORT TO EXCEL (PICKLIST AND AUTO COMPLETE DATA)
							$final_imp_pick      = array_combine( $pick_imp_key ?? [], $pick_imp_val ?? []);
							$this->export_pick_arr[$label_id]   = $final_imp_pick;
							//CODE END FOR TIME SHEET TABLE DATA EXPORT TO EXCEL (PICKLIST AND AUTO COMPLETE DATA)
						}
						
	  					//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_display_val 	   = "CONCAT(".str_replace(",",'," ~ ",',$pick_display).") as auto_list_pick";
					if($pick_table === "cw_sap_personal_area"){							
						$pick_query = "select $auto_prime_id,$auto_dispaly_value,$pick_display_val from $pick_table where $pick_table.personal_code in (".$this->logged_area_access.") $where_condition";
					}else
					if($pick_table === "cw_sap_wbs"){
						$qry = "wbs_element";
						if($label_id === 'network_id'){
							$qry = "network_id";
						}
						$pick_query = "select $auto_prime_id,$auto_dispaly_value,$pick_display_val from $pick_table inner join cw_pay_structure on cw_pay_structure.$qry = $pick_table.$auto_prime_id where $pick_table.trans_status = 1 and cw_pay_structure.personal_code in (".$this->logged_area_access.") $where_condition";
					}else
					if($pick_table === "cw_sap_activity"){
						$pick_query = "select $auto_prime_id,$auto_dispaly_value,$pick_display_val from $pick_table inner join cw_pay_structure on cw_pay_structure.activity_no = $pick_table.$auto_prime_id where $pick_table.trans_status = 1 and cw_pay_structure.personal_code in (".$this->logged_area_access.") $where_condition";
					}else
					if($pick_table === "cw_sap_position"){
						$pick_query = "select $auto_prime_id,$auto_dispaly_value,$pick_display_val from $pick_table inner join cw_pay_structure on cw_pay_structure.position = $pick_table.$auto_prime_id where $pick_table.trans_status = 1 and cw_pay_structure.personal_code in (".$this->logged_area_access.") $where_condition";
					}else{
						$pick_query = "select $auto_prime_id,$auto_dispaly_value,$pick_display_val 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);
						$pick_val   = array_column($pick_result ?? [], 'auto_list_pick');
						$final_pick = array_combine( $pick_key ?? [], $pick_val ?? []);
					}
					$this->master_pick[$label_id]   = $final_pick;
					// $final_pick = array("" => "---- $label_name ----") + $final_pick;
					$this->all_pick[$prime_form_id] = $final_pick;
					//CODE START FOR TIME SHEET TABLE DATA EXPORT TO EXCEL (PICKLIST AND AUTO COMPLETE DATA)
					$pick_imp_key        = array_column($pick_result ?? [], 'auto_list_pick');
					$pick_imp_val        = array_column($pick_result ?? [], $auto_dispaly_value);
					$final_imp_pick      = array_combine( $pick_imp_key ?? [], $pick_imp_val ?? []);
					$this->export_pick_arr[$label_id]   = $final_imp_pick;
					//CODE END FOR TIME SHEET TABLE DATA EXPORT TO EXCEL (PICKLIST AND AUTO COMPLETE DATA)
				}
				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,'prime_form_id'=>$prime_form_id);
					}
				}
			}
		}
		$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_user_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";
			}
		}		
		$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' => 'Invalid Request..'));
			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');
		$depen_pick_input = $this->input->post('depen_pick_input');
	
		$form_query       = 'select * from cw_form_setting where prime_form_id in ("'.$prime_form_id.'","'.$depend_hidden_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]){
			$prime_module_id     = $form_result[$prime_form_id]['prime_module_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'];
				// $depand_display = $form_result[$depend_hidden_id]['auto_dispaly_value'];
				$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->post('pick_table');
				$table_column2 	= $this->input->post('table_column2');
				$pick_tbl_val 	= $this->input->post('pick_tbl_val');
				$depen_select 	= $this->input->post('depen_select');

				//DR CODE FOR PAY STRUCTURE PERSONAL AREA BASED WBS BASED ACTIVITY NUMBER FETCH
				$per_area 	         = $this->input->post('per_area');
				$wbs_element 	     = $this->input->post('wbs');
				$position 	         = $this->input->post('position');
				$pay_struct_join = "";
				$pay_struct_whre = "";
				$pay_struct_grp  = "";
				//QUERY FOR PERSONAL AREA BASED WBS FETCH (BASED ON PAY STRUCTURE)
				if($label_id_val === "wbs_element" && $this->control_name !== "pay_structure" && $this->control_name !== "pay_structure_report"){
					$pay_struct_join  = ' inner join cw_pay_structure on cw_pay_structure.'.$label_id_val.' = '.$pick_table.'.'.$auto_prime_id;
					$pay_struct_whre  = ' and cw_pay_structure.'.$depen_pick_input.' = "'.$per_area.'" and cw_pay_structure.trans_status = 1 and cw_pay_structure.personal_code in ('.$this->logged_area_access.') ';
					// and cw_pay_structure.status=1
					$pay_struct_grp   = ' GROUP BY '.$pick_table.'.'.$auto_prime_id;
				}else//QUERY FOR WBS BASED ACTIVITY NO FETCH (BASED ON PAY STRUCTURE)
				if($label_id_val === "activity_no" && $this->control_name !== "pay_structure" && $this->control_name !== "cw_monthly_input_fms"){					
					$pay_struct_join  = ' inner join cw_pay_structure on cw_pay_structure.'.$label_id_val.' = '.$pick_table.'.'.$auto_prime_id;
					$pay_struct_whre  = ' and cw_pay_structure.'.$depen_pick_input.' = "'.$wbs_element.'" and cw_pay_structure.position = "'.$position.'" and cw_pay_structure.trans_status = 1 and cw_pay_structure.personal_code in ('.$this->logged_area_access.')';
					$pay_struct_grp   = ' GROUP BY '.$pick_table.'.'.$auto_prime_id;
				}
				// if($pick_table === "cw_sap_wbs"){
				// 	$wbs_cond       = ' and FIND_IN_SET('.$pick_table.'.wbs_personal_area_id, "'.$this->logged_area_access.'")';
				// }else{
				// 	$wbs_cond       = " ";
				// }
				$depand_join 	= " inner join $pick_table_sec on $pick_table_sec.$depand_tbl1 = $pick_table.$depand_tbl2 $pay_struct_join";
				$depand_where 	= " $pick_table_sec.trans_status = 1 and $pick_table_sec.$depand_display = \"$depen_select\" $pay_struct_whre";
			}
			$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 label";
			$display_list  = "CONCAT(".str_replace(",",'," - ",',$pick_display_value).") as display_name";

			$suggest_query = "select $pick_table.$auto_prime_id as value,$pick_table.$auto_dispaly_value,$auto_list,$display_list from $pick_table $depand_join where $depand_where";

			$col_list      = explode(",",$pick_list ?? "");
			 if($depand_where){
				$suggest_query .= " and ";
			 }
			$where_query  = "";
			foreach($col_list as $col){
				$where_query .= $col.' like "%'.$search_term.'%" or ';
			}
			$where_query    = rtrim($where_query," or ");
			$suggest_query .= '('.$where_query.')';
			$suggest_query .= $where_condition;

			//FOR LOAN EMPLOYEE CODE AUTOCOMPLETE 
			if($prime_module_id === "loan" && $label_id_val === "employee_code"){
				$suggest_query .= ' and cw_employees.termination_status = 0 and entry_flag="e" and cw_employees.personal_code in ('.$this->logged_area_access.') ';
			}

			//DR CODE FOR PAY STRUCTURE WBS BASED ACTIVITY NUMBER FETCH
			$suggest_query .= $pay_struct_grp;
			//DR CODE END
			$suggest_query .= ' limit 0,50';
			//echo $suggest_query; die;
			$suggest_data   = $this->db->query("CALL sp_a_run ('SELECT','$suggest_query')");
			$suggest_result = $suggest_data->result_array();
			$suggest_data->next_result();
		}
		if(empty($suggest_result[0])){
			$suggestions[] = array('value' => "0", 'label' => "No data found for this search");
		}
		echo json_encode($suggest_result);		
	}
	
	//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";
				//$cf_id            = "prime_".$module_name."_cf_id";
				//$cf_table_name    = $this->db->dbprefix($module_name."_cf");
				
				$join_module_name      = str_replace("cw_","",$line_join_table);
				$join_prime_id         = "prime_".$join_module_name."_id";
				//$join_cf_id            = "prime_".$join_module_name."_cf_id";
				//$join_cf_table_name    = $this->db->dbprefix($join_module_name."_cf");
				//inner join  $join_cf_table_name on $line_join_table.$join_prime_id = $join_cf_table_name.$join_prime_id
				//inner join  $join_cf_table_name on $line_join_table.$join_prime_id = $join_cf_table_name.$join_prime_id
				//inner join $cf_table_name on $line_prime_table.$prime_id = $cf_table_name.$prime_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";
				//$cf_id            = "prime_".$module_name."_cf_id";
				//$cf_table_name    = $this->db->dbprefix($module_name."_cf");			
				//inner join $cf_table_name on $condition_table.$prime_id = $cf_table_name.$prime_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' => 'Invalid Request..','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= $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= $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' => 'Invalid Request..','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' => 'Invalid Request..'));
				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 = "";

		$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);
				$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' => 'Invalid Request..','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);		
		
		$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 = "'.$this->control_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' => 'Invalid Request..','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");
		$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){
		$this->get_rowset_form_info();
		$view_qry    = 'select * from cw_form_view_setting where prime_form_view_id = "'.$view_id.'" and prime_view_module_id = "'.$this->control_name.'" and  form_view_type = "3" and trans_status = 1';
		$view_data   = $this->db->query("CALL sp_a_run ('SELECT','$view_qry')");
		$view_result = $view_data->result();
		$view_data->next_result();
		$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      = $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";

		$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 = "'.$this->control_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){
					$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;
		$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;
				$field_type  = $this->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 = $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>";
			}
			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>";
			}
			if($this->control_name === 'employees'){
				if((int)$this->logged_user_role === 1 || (int)$this->logged_user_role === 2){
					$tr_line .= "<tr>$td_line<td>$illustration_btn $edit_btn $remove_btn</td></tr>";
				}else{
					$tr_line .= "<tr>$td_line<td>$illustration_btn</td></tr>";
				}	
			}else{
				$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' => 'Invalid Request..','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);
		}else
		if($module_id === "loan"){
			echo $this->do_loan_excel_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 === "time_log"){
		 	echo $this->do_excel_timelog_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{
			echo $this->do_excel_import($import_id,$import_type);
		}
	}
	//Import Time log 
	public function do_excel_timelog_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 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,auto_prime_id,auto_dispaly_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 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 = "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.'"';
												// echo "$pick_query<br>";
												$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_cell_formate = $excel_obj->getActiveSheet()->getCell($col_key.$i)->getStyle()->getNumberFormat()->getFormatCode();
									$cell_formate = str_replace("[$-14009]","",$excel_cell_formate);
									$cell_formate = trim(strtoupper(str_replace(";@","",$cell_formate)));
									$cell_formate = str_replace('\-', '-', $cell_formate);
									if($cell_formate === "DD/MM/YYYY" || $cell_formate === "DD-MM-YYYY"){
										if($cell_formate === "DD/MM/YYYY"){
											$year_month_rslt = explode('/', $col_value ?? "");
										}else
										if($cell_formate === "DD-MM-YYYY"){
											$year_month_rslt = explode('-', $col_value ?? "");
										}
										$date  			 = $year_month_rslt[0];
										$month  	     = $year_month_rslt[1];
										$year			 = $year_month_rslt[2];
										$tot_days 		 = cal_days_in_month(CAL_GREGORIAN,$month,$year);
										if(((int)$date  === 0) || ((int)$month === 0) || ((int)$year === 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;
										}else
										if((int)$month > 12){
											$err_column_array['error']["$excel_line_value$i"] = $view_name;
											$msg_line = "Invalid Month... Please map The Date Format Like (DD/MM/YYYY)";
											$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
										}else
										if((int)$date > (int)$tot_days){
											$err_column_array['error']["$excel_line_value$i"] = $view_name;
											$msg_line = "Invalid date... Please map The Date Format Like (DD/MM/YYYY)";
											$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line; 
										}
									}else{
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
										$msg_line = "Invalid Date Format... 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);
										$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($sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));
									}else
									if($field_type === 13){
										$get_datetime = trim(date('Y-m-d H:i:s',Date::PHPToExcel($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
										$newhours = date('Y-m-d H:i:s', strtotime($get_datetime. ' -5 hours'));
										$get_cell_value = date('Y-m-d H:i:s', strtotime($newhours. ' -30 minutes'));
									}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){
											// 	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 === 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";
								// echo "$exist_query\n";
								$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)";
									// echo "$prime_query\n";
									$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.'"';
										// echo "$upd_query\n";
										$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->leave_financial_info;
	// 	$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        = "";

	// 	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{
	// 			//GET EMPLOYEE DETAILS FROM EMPLOYEE MASTER
	// 			$emp_name_qry    = 'select employee_code,role as category,emp_name,date_of_joining,department,approval_type,first_level_approval,second_level_approval,termination_status,resignation_date from cw_employees where cw_employees.role = "'.$category.'" and (cw_employees.termination_status = 1 or cw_employees.resignation_date between "'.$salary_start_date.'" and "'.$salary_end_date.'") and cw_employees.trans_status = 1';
	// 			$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());	
	// 			//time entry details for that 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,employee_code,att_date,entry_flag,update_flag from cw_time_entry inner join cw_shift_master on cw_shift_master.prime_shift_master_id = cw_time_entry.shift_id where employee_code = "'.$employee_code.'" and att_date between "'.$salary_start_date.'" and "'.$salary_end_date.'" and 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();	

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

	// 			// //GET SHIFT NAME FROM SHIFT MASTER
	// 			// $shift_name_qry   = 'select prime_shift_master_id,shift_name,shift_status 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;
	// 			//     return $result;
	// 			// }, array());	
	// 			// print_r($shift_name_arr);die;
	// 			//$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';			
	// 			$excel_format        = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
	// 			$excel_format_result = $excel_format->result();
	// 			$excel_format->next_result();
	// 			// print_r($excel_format_result);die;
	// 			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();
	// 				$prime_query_value    = "";
	// 				$prime_upd_value      = "";
					
	// 				// print_r($opening_used_arr);die;
	// 				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;
	// 					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($sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));
	// 								// echo "DR::$get_cell_value";
	// 								// 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;

	// 								// }
	// 							}else
	// 							if($field_type === 13){
	// 								$get_cell_value = trim(date('Y-m-d H:i:s',PHPExcel_Shared_Date::ExcelToPHP($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 && $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){
	// 										// $err_status_info["Excel Row"] = $row;
	// 										$err_status_info["$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){
	// 												// $err_status_info["Excel Row"] = $row;
	// 												// $err_status_info['status']    = "Invalid $get_cell_value";
	// 												$err_status_info["$row"] = "Invalid $get_cell_value";
	// 												$message                 = "Invalid $get_cell_value";
	// 												$status                  = FALSE;
	// 												$picklist_sts            = FALSE;
	// 											}
	// 										}
	// 									}
	// 								}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 Row"] = $row;
	// 										// $err_status_info['status']    = "Invalid $get_cell_value";
	// 										$err_status_info["$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_status_info["Excel Row"] = $row;
	// 											// $err_status_info['status']    = "Invalid $get_cell_value";
	// 											$err_status_info["$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;
	// 									$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']));
	// 									$approval_type    = $emp_name_arr[$employee_code]['approval_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'];
										
	// 								}
	// 								if($excel_line_column_name === 'shift_name'){
	// 									$shift_name     = $get_cell_value;
	// 								}
	// 								if($excel_line_column_name === "entry_date"){
	// 									$entry_date     = date('Y-m-d',strtotime($get_cell_value));
	// 								}
	// 								if($excel_line_column_name === "ot_in_time"){
	// 									$ot_in_time     = date("H:i", strtotime($get_cell_value));
	// 								}
	// 								if($excel_line_column_name === "ot_out_time"){
	// 									$ot_out_time    = date("H:i", strtotime($get_cell_value));
	// 								}
	// 								if($excel_line_column_name === "ot_type"){
	// 									$ot_type        = date("H:i", strtotime($get_cell_value));
	// 								}
	// 								if($excel_line_column_name === "reason"){
	// 									$reason         = $get_cell_value;
	// 								}
	// 								// $get_cell_value    = str_replace("'",'^', $get_cell_value);
	// 								// $prime_column_val .= $excel_line_column_name . ",";
	// 								// $prime_cell_val   .= '"' . $get_cell_value . '",';

	// 								// echo "DR::$prime_cell_val::";

	// 								// if(empty($exist_column_name)){
	// 								// 	 if($mandatory_field === 1){
	// 								// 		$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'"';
	// 								// 	}
	// 								// }else{
	// 								// 	if(in_array($excel_line_column_name,$exist_column_name)){
	// 								// 		$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'"';
	// 								// 	}
	// 								// }
	// 							}
	// 						}
	// 					}
	// 					if(!$check_emp_code){
	// 						$err_column_array['error']["$row"] = "This Employee Code ($employee_code) or Employee Name not Present in the Employee Master? Please Check it..!";
	// 					}else{
	// 						$check_ot_exist_qry    = 'select count(*) 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 = "'.$ot_type.'" and cw_overtime_entry.trans_status = 1';
	// 						$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;
	// 						//QRY FOR CHECK TIME ENTRY TABLE
	// 						// $time_entry_qry      = 'select total_excess_hours,approved_ot_mins 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();

	// 						// $total_excess_hours  = (int)$time_entry_result[0]->total_excess_hours;
	// 						// $approved_ot_mins    = (int)$time_entry_result[0]->approved_ot_mins;

	// 						//CHECK A VALID SHIFT IMPORT OR NOT
	// 						// $check_shift_name    = $shift_name_arr[$shift_name];
	// 						if($ot_exist_count){
	// 							$err_column_array['error']["$row"] = "Same Date Already Exist in Overtime Entry Table..!!";
	// 						}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']["$row"] = "Attendance Date Should not be Greater than Date of Joining Please Check it..!!";
	// 										$exist_count++;
	// 									}
	// 								}else{
	// 									//check month day for this category
	// 									// $month_day_info   = $this->month_day_info($category,$starting_date,$ending_date);

	// 									// if(count($month_day_info)){
	// 										// $salary_start_date     = date("Y-m-d",strtotime($month_day_info["salary_start_date"]));
	// 										// $salary_end_date       = date("Y-m-d",strtotime($month_day_info["salary_end_date"]));
	// 										if($active_sts === 0){
	// 											if($resign_date){
	// 												if($resign_date < $salary_start_date){
	// 													$err_column_array['error']["$row"] = "Don't Import Resigned Employee for this Attendance Month? Please Check it..!!";
	// 												}
	// 											}else{
	// 												$err_column_array['error']["$row"] = "Please Map Resigned Date for this Employee? Please Check it..!!";
	// 											}
	// 										}
	// 										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']["$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 
	// 												// $time_entry_rslt  = $this->check_time_entry_details($employee_code,$entry_date);
	// 												if(!$time_entry_arr[$employee_code][$entry_date]){
	// 													(int)$exist_count += 1;
	// 													if($exist_count === 1){
	// 														$err_column_array['error']["$row"] = "In this Date this Employee not Available in OT Approval Please Check Attendance Table..!!";
	// 														$exist_count++;
	// 													}
	// 												}else{
	// 													// $check_ot_appr    =  $this->check_time_entry_details($employee_code,$entry_date,$time_entry_rslt);
	// 													$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            = $time_entry_arr[$employee_code][$entry_date]['early_in'];
	// 													// $excess_out          = $time_entry_arr[$employee_code][$entry_date]['excess_out'];
	// 													$shift_id         = $time_entry_arr[$employee_code][$entry_date]['shift_id'];

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

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

	// 													// $ot_in_time       = $shift_to_time;

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

	// 													if($punch_out && $ot_in_time && $ot_out_time){
	// 														if($shift_from_time > $ot_in_time){
	// 															(int)$exist_count += 1;
	// 															if($exist_count === 1){
	// 																$err_column_array['error']["$row"] = "OT Out Time should not be Greater than Punch Out Time..!!";
	// 																$exist_count++;
	// 															}
	// 														}else
	// 														if($punch_out < $ot_out_time){
	// 															(int)$exist_count += 1;
	// 															if($exist_count === 1){
	// 																$err_column_array['error']["$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']["$row"] = "On this Day You are not Eligible for Apply OT Request..!Please Check it?..!!";
	// 																	$exist_count++;
	// 																}
	// 															}else{
	// 																$ot_in_date   = date("Y-m-d H:i",strtotime($entry_date.$ot_in_time));
	// 																if($shift_status === 1 && $shift_status === 3){
	// 																	if($ot_in_time >= $ot_out_time){
	// 																		(int)$exist_count += 1;
	// 																		if($exist_count === 1){
	// 																			$err_column_array['error']["$row"] = "OT Out Time should not be Greater than Punch Out Time..!!";
	// 																			$exist_count++;
	// 																		}
	// 																	}else{
	// 																		$ot_out_date   = date("Y-m-d H:i",strtotime($entry_date.$ot_out_time));
	// 																	}
																		
	// 																}else
	// 																if($shift_status === 2){
	// 																	if($ot_in_time <= $ot_out_time){
	// 																		(int)$exist_count += 1;
	// 																		if($exist_count === 1){
	// 																			$err_column_array['error']["$row"] = "OT Out Time should not be Greater than Punch Out Time..!!";
	// 																			$exist_count++;
	// 																		}
	// 																	}else{
	// 																		$ot_out_date   = date("Y-m-d H:i",strtotime('+1 days',strtotime($entry_date.$ot_out_time)));
	// 																	}
	// 																}
	// 																if($ot_in_date && $ot_out_date){
	// 																	$date_arr    = date_diff($ot_in_date, $ot_out_date);
	// 																	$time_hr     = $date_arr['h'];
	// 																	$time_min    = $date_arr['m'];
	// 																	$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']["$row"] = "In this Attendance Date Total Excess Hours 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{
	// 																			$prime_req_value = '"'.$employee_code.'","'.$category.'","'.$emp_doj.'","'.$department.'","'.$approval_type.'","'.$first_level.'","'.$second_level.'","'.$applied_on.'","'.$entry_date.'","'.$shift_name.'","'.$punch_in.'","'.$punch_out.'","'.$ot_in_time.'","'.$ot_out_time.'","'.$total_hours.'","'.$ot_type.'","'.$shift_status.'","1","1","1","'.$prime_financial_id.'","'.$reason.'","'.$this->logged_id.'","'.$created_on.'"';
	// 																				$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,excess_work,ot_type,shift_status,first_approval_status,second_approval_status,approval_status,financial_setting_id,reason,trans_created_by,trans_created_date";
							
	// 																				$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        = $request_ins_info[0]->ins_id;

	// 																				//OT ENTRY INSERT QRY	
	// 																				$ot_entry_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.'","'.$total_hours.'","'.$ot_type.'","1","'.$this->logged_id.'","'.$created_on.'"),(';

	// 																				$prime_app_value .= '"'.$insert_id.'","'.$employee_code.'","'.$category.'","'.$emp_doj.'","'.$department.'","'.$approval_type.'","'.$first_level.'","'.$second_level.'","'.$applied_on.'","'.$entry_date.'","'.$shift_name.'","'.$punch_in.'","'.$punch_out.'","'.$ot_in_time.'","'.$ot_out_time.'","'.$total_hours.'","'.$ot_type.'","'.$shift_status.'","1","1","1","'.$prime_financial_id.'","'.$reason.'","'.$this->logged_id.'","'.$created_on.'"),(';



	// 																				$status_info['Status'] = "Inserted to DB";
	// 																				$status_array[] = $status_info;
	// 																		}
	// 																	}
	// 																}
	// 															}
	// 														}	
	// 													}
	// 												}
	// 											}
	// 										}	
	// 									// }else{
	// 									// 	$err_column_array['error']["$row"] = "Please Set Month Day for this Category..!!";
	// 									// }
	// 								}
	// 							}else{
	// 								$err_column_array['error']["$row"] = "Please Add Date of Joining for this Employee..!!";
	// 							}
	// 						}
								
							
	// 						// }else{
								
	// 						// }		
	// 					}
	// 				}
	// 				$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 are Not Imported",'table_info'=>$table_info));
	// 				}else{
	// 					//FOR OT REQUEST INSERT TO OT REQUEST TABLE
	// 					if($prime_app_value){
	// 						$prime_app_value        = rtrim($prime_app_value,"),(");	
	// 						$prime_column_val       = "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,excess_work,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_column_val) VALUES ($prime_app_value)";						
	// 						$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();
					
	// 						//FOR OT REQUEST UPDATE TO OT ENTRY TABLE
	// 						// if($approval_ins_rslt){
	// 						// 	$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) VALUES '.$prime_upd_value.' 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)';
	// 						// 	$shift_import_upd_info  = $this->db->query("CALL sp_a_run ('RUN','$shift_import_upd_qry')");
	// 						// }
	// 						$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();	
	// 	// $punch_in              = $time_entry_result[0]->punch_in;
	// 	// $punch_out             = $time_entry_result[0]->punch_out;
	// 	// $early_in              = $time_entry_result[0]->early_in;
	// 	// $excess_out            = $time_entry_result[0]->excess_out;
	// 	// $shift_id              = $time_entry_result[0]->shift_id;
	// 	// $total_excess_hours    = $time_entry_result[0]->total_excess_hours;
	// 	// $whole_day_status      = $time_entry_result[0]->whole_day_status;
	// 	// $shift_from_time       = date("H:i",strtotime($time_entry_result[0]->from_time));
	// 	// $shift_to_time         = date("H:i",strtotime($time_entry_result[0]->to_time));
	// 	// $shift_status          = $time_entry_result[0]->shift_status;

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

	// function check_total_time(){
	// 	$total_hours           = $this->input->post('total_hours');
	// 	$shift_name            = $this->input->post('shift_name');
	// 	$category              = $this->input->post('category');
	// 	$employee_code         = $this->input->post('employee_code');
	// 	$ot_type               = $this->input->post('ot_type');
	// 	$entry_date            = date('Y-m-d',strtotime($this->input->post('entry_date')));

	// 	$ot_hours_sts          = $this->ot_hours_check($total_hours,$shift_name,$category,$employee_code,$ot_type,$entry_date);
	// 	if((int)$ot_hours_sts){
	// 		echo json_encode(array('success' => TRUE,  'total_hours' => $total_hours));
	// 	}	
	// }

	// function ot_hours_check($total_hours,$shift_name,$category,$employee_code,$ot_type,$entry_date){
	// 	//HOURS TO MIN
	// 	$total_ot_mins         = $this->time_to_min($total_hours);

	// 	$total_hours           = date("H:i", strtotime($total_hours));		
	// 	//GTE DEFAULT FINANCIAL YEAR
	// 	$financial_info        = $this->leave_financial_info;
	// 	$prime_financial_id    = $financial_info[0]->prime_leave_financial_year_id;	
	// 	$starting_date         = date('Y-m-d',strtotime($financial_info[0]->starting_date));	
	// 	$ending_date           = date('Y-m-d',strtotime($financial_info[0]->ending_date));	
	// 	//check month day for this category
	// 	$month_day_info        = $this->month_day_info($category,$starting_date,$ending_date);

	// 	if(count($month_day_info)){
	// 		$salary_start_date     = date("Y-m-d",strtotime($month_day_info["salary_start_date"]));
	// 		$salary_end_date       = date("Y-m-d",strtotime($month_day_info["salary_end_date"]));

	// 		$check_sts             = false;
	// 		if($entry_date >= $salary_start_date && $entry_date <= $salary_end_date){
	// 			$check_sts         = true;
	// 		}
	// 		if($check_sts){
	// 			$time_entry_qry      = 'select entry_flag,update_flag,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 from cw_time_entry where employee_code = "'.$employee_code.'" and att_date = "'.$entry_date.'" and 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();	

	// 			$total_excess_hours  = $time_entry_result[0]->total_excess_hours;
	// 			$entry_flag          = $time_entry_result[0]->entry_flag;
	// 			$update_flag         = $time_entry_result[0]->update_flag;
	// 			if(($entry_flag === "U" || $update_flag === "U") && ($entry_flag !== "W" && $update_flag !== "W")){
	// 				echo json_encode(array('success' => FALSE, "message" => "On this Day You are not Eligible for Apply OT Request..!Please Contact Admin?"));
	// 			}else{
	// 				if($total_excess_hours < $total_hours){
	// 					echo json_encode(array('success' => FALSE, "message" => "Total OT Hours should not Exceeded the Excess Hours ..!"));
	// 				}else{
	// 					return true;
	// 				}
	// 			}
	// 		}else{
	// 			echo json_encode(array('success' => FALSE, "message" => "Don't Add Your Overtime Request Because Payroll should be Processed for this Month...!"));
	// 		}
	// 	}else{
	// 		echo json_encode(array('success' => FALSE, 'message' => "Please Set Month Day for this Category..."));
	// 		exit(0);
	// 	}	
	// }
	// function time_to_min($time) {
	//     $timeArr = explode(':', $time);
	//     $time_min = round(($timeArr[0]*60) + ($timeArr[1]) + ($timeArr[2]/60));
	// 	// $tot_hours = floor($time_min / 60).':'.(int)($time_min -   floor($time_min / 60) * 60);
	//     return $time_min;
	// }
	//import validation and checking updated
	public function do_excel_shift_import($import_id){
		$prime_financial_id  = $this->leave_financial_info[0]->prime_leave_financial_year_id;
		$starting_date       = date('Y-m-d',strtotime($this->leave_financial_info[0]->starting_date));	
		$ending_date         = date('Y-m-d',strtotime($this->leave_financial_info[0]->ending_date));	
		$emp_name_arr        = ""; 
		$shift_import_arr    = "";
		$shift_name_arr      = "";
		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{
				//GET EMPLOYEE NAME FROM EMPLOYEE MASTER
				$emp_name_qry    = 'select employee_code,emp_name,date_of_joining from cw_employees where trans_status = 1';
				$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());	
                
				//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());	
				//$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,auto_prime_id,auto_dispaly_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();
					$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;
						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($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',PHPExcel_Shared_Date::ExcelToPHP($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';
										}	
										// echo "BSK $pick_query <br/>";
										$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){
											// $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;
											$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 === 'component_value'){
										$component_value = $get_cell_value;
									}*/
									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_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)));

									}
									
									// $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(!$check_emp_code){
						// 	$err_column_array['error']["$row"] = "This Employee Code ($employee_code) or Employee Name not Present in the Employee Master? Please Check it..!";
						// }
						// else{
							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_reduce($shift_import_exist_rslt ?? [], function ($result, $arr) {
								    $result[$arr['employee_code']][$arr['shift_date']] = $arr;
								    return $result;
								}, array());	

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

									//CHECK A VALID SHIFT IMPORT OR NOT
									$check_shift_name  = $shift_name_arr[$shift_name];
									//GET EMLOYEE DATE OF JOINING
									$emp_doj           = $emp_name_arr[$employee_code]['date_of_joining'];
									if($emp_doj > $shift_date){
										(int)$exist_count += 1;
										if($exist_count === 1){
											$err_column_array['error']["$row"] = "Shift Date Should not 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']["$shift_column_value$row"] = "In Valid Shift Name Please Check it!!";
											$exist_count++;
										}
									}else
									if($exist_date){
										//UPD 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{
										$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"] = "In Valid 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) VALUES '.$prime_upd_value.' 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)';
							$shift_import_upd_info  = $this->db->query("CALL sp_a_run ('RUN','$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";
							
							$prime_query            = "insert into $this->prime_table ($prime_column_val) VALUES ($prime_query_value)";						
							$insert_info            = $this->db->query($prime_query);
						}

						$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_weekoff_import($import_id){
		$prime_financial_id    = $this->leave_financial_info[0]->prime_leave_financial_year_id;
		$starting_date         = date('Y-m-d',strtotime($this->leave_financial_info[0]->starting_date));	
		$ending_date           = date('Y-m-d',strtotime($this->leave_financial_info[0]->ending_date));	
		$emp_name_arr          = "";
		$time_entry_arr        = "";
		$leave_entry_arr       = "";
		$permission_entry_arr  = "";
		$on_duty_entry_arr     = "";
		$shift_import_arr      = ""; 
		$weekoff_import_arr    = "";
		$weekoff_id_arr        = "";
		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
				$last_payroll_date = $this->last_payroll_status($starting_date,$ending_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 > "'.$last_payroll_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());	
				
				//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.att_date > "'.$last_payroll_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['att_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 > "'.$last_payroll_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 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.permission_date > "'.$last_payroll_date.'"';
				$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_reduce($permission_entry_result ?? [], function ($result, $arr) {
				    $result[$arr['employee_code']][$arr['permission_date']] = $arr['permission_date'];
				    return $result;
				}, array());

				//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 > "'.$last_payroll_date.'"';
				$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_reduce($on_duty_entry_result ?? [], function ($result, $arr) {
				    $result[$arr['employee_code']][$arr['on_duty_date']] = $arr['on_duty_date'];
				    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,shift_date,shift_name from cw_shift_import inner join cw_employees on cw_employees.employee_code = cw_shift_import.employee_code where cw_shift_import.trans_status = 1 and cw_shift_import.shift_date > "'.$last_payroll_date.'" and cw_shift_import.financial_setting_id ="'.$prime_financial_id.'" and (cw_employees.termination_status = 0 or cw_employees.resignation_date > "'.$last_payroll_date.'")';
				$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_import_arr          = array_reduce($shift_import_exist_result ?? [], function ($result, $arr) {
				    $result[$arr['employee_code']][$arr['shift_date']] = $arr['shift_name'];
				    return $result;
				}, array());

				//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.'"';
				$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_import_arr = array_reduce($weekoff_import_exist_result ?? [], function ($result, $arr) {
				    $result[$arr['employee_code']][$arr['weekoff_date']] = $arr['weekoff_type'];
				    return $result;
				}, array());	

				//ARRAY FOR GET PRIME WEEKOFF IMPORT ID FOR UPDATE A SAME WEEKOFF DATE BUT DAY TYPE CHANGE 
				$weekoff_id_arr     = array_reduce($weekoff_import_exist_result ?? [], function ($result, $arr) {
				    $result[$arr['employee_code']][$arr['weekoff_date']] = $arr['prime_weekoff_import_id'];
				    return $result;
				}, array());	
				
				//$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,auto_prime_id,auto_dispaly_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();
					$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($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',PHPExcel_Shared_Date::ExcelToPHP($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.'"';
										}	
										// echo "BSK $pick_query <br/>";
										$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){
											// $status_info["$excel_line_value$row"] = "Invalid $get_cell_value";
											$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){
											// $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;
											$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){
									//$status_info[$excel_line_column_name] = $get_cell_value;
									/*if($excel_line_column_name === 'component_value'){
										$component_value = $get_cell_value;
									}*/
									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 === 'weekoff_type'){
										$shift_name_col_name  = $excel_line_value;
										$weekoff_type  = (int)$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 && $employee_name && $from_date && $to_date && $weekoff_type){
							$period = new DatePeriod(
							     new DateTime("$from_date"),
							     new DateInterval('P1D'),
							     new DateTime("$after_to_date")
							);
						}
						// check_shift_import_exist($employee_code,$employee_name,$from_date,$to_date,$shift_name,$period);
						$created_on  = date("Y-m-d H:i:s");
						$exist_count = 0;
						foreach ($period as $key => $value) {
							$weekoff_date           = $value->format('Y-m-d');
							//GET EMLOYEE DATE OF JOINING
							$emp_doj                = $emp_name_arr[$employee_code]['date_of_joining'];

							$exist_date             = $shift_import_arr[$employee_code][$weekoff_date];
							//CHECK A VALID WEEKOFF TYPE FOR TO IMPORT OR NOT
							$check_weekoff_type     = (int)$weekoff_import_arr[$employee_code][$weekoff_date];
							// CONDITION FOR CHECK A TIME ENTRY EXIST IF EXIST NOT UPDATE TO SHIFT IMPORT
							$check_time_entry       = $time_entry_arr[$employee_code][$weekoff_date];
							// CONDITION FOR CHECK A LEAVE ENTRY EXIST IF EXIST NOT UPDATE TO SHIFT IMPORT
							$check_leave_entry      = $leave_entry_arr[$employee_code][$shift_date];
							// CONDITION FOR CHECK A PERMISSION ENTRY EXIST IF EXIST NOT UPDATE TO SHIFT IMPORT
							$check_permission_entry = $permission_entry_arr[$employee_code][$shift_date];
							// CONDITION FOR CHECK A ON DUTY ENTRY EXIST IF EXIST NOT UPDATE TO SHIFT IMPORT
							$check_on_duty_entry    = $on_duty_entry_arr[$employee_code][$shift_date];

							if($emp_doj > $weekoff_date){
								(int)$exist_count += 1;
								if($exist_count === 1){
									$err_column_array['error']["$row"] = "Weekoff Date Should not be Greater than Date of Joining Please Check it..!!";
									$exist_count++;
								}
							}	
							else
							if($check_weekoff_type){
								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){
										$shift_date = $value->format('d-m-Y');
										$err_column_array['error']["$row"] = "$employee_code Time Entry Exist in Date of $shift_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){
										$shift_date = $value->format('d-m-Y');
										$err_column_array['error']["$row"] = "$employee_code Leave Entry Exist in Date of $shift_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){
										$shift_date = $value->format('d-m-Y');
										$err_column_array['error']["$row"] = "$employee_code Permission Entry Exist in Date of $shift_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){
										$shift_date = $value->format('d-m-Y');
										$err_column_array['error']["$row"] = "$employee_code On Duty Entry Exist in Date of $shift_date";
										$exist_count++;
									}
								}else
								if($check_weekoff_type === $weekoff_type){
									(int)$exist_count += 1;
									if($exist_count === 1){
										$week_date = $value->format('d-m-Y');
										$err_column_array['error']["$row"] = "$employee_code Already Weekoff Imported in Date of $week_date? Please Check Weekoff Import..!!";
										$exist_count++;
									}
								}else
								if($check_weekoff_type === $weekoff_type){
									(int)$exist_count += 1;
									if($exist_count === 1){
										$week_date = $value->format('d-m-Y');
										$err_column_array['error']["$row"] = "$employee_code Already Weekoff Imported in Date of $week_date? Please Check Weekoff Import..!!";
										$exist_count++;
									}
								}else
								if($weekoff_excel_exist_arr[$employee_code][$weekoff_date]){
									$week_date = $value->format('d-m-Y');
									$err_column_array['error']["$row"] = "$employee_code Already Weekoff Imported in Date of $week_date? Please Check Weekoff Import..!!";
									$exist_count++;
								}else{
									$weekoff_id = $weekoff_id_arr[$employee_code][$weekoff_date];
									$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;
							}	
						} 
					}
					$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("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));
						}
					}
				}
			}
		}
	}
	public function do_excel_manual_punch_import($import_id,$category,$process_month){
		$prime_financial_id    = $this->leave_financial_info[0]->prime_leave_financial_year_id;
		$starting_date         = date('Y-m-d',strtotime($this->leave_financial_info[0]->starting_date));	
		$ending_date           = date('Y-m-d',strtotime($this->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   = "";
		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
				// $last_payroll_date = $this->last_payroll_status($starting_date,$ending_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';
				// echo "shift_import_exist_qry::$shift_import_exist_qry";die;
				$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());	

				//ARRAY FOR GET PRIME WEEKOFF IMPORT ID FOR UPDATE A SAME WEEKOFF DATE BUT DAY TYPE CHANGE 
				// $weekoff_id_arr            = array_reduce($weekoff_import_exist_result, function ($result, $arr){
				//     $result[$arr['employee_code']][$arr['weekoff_date']] = $arr['prime_id'];
				//     return $result;
				// }, array());	
				
				//$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,auto_prime_id,auto_dispaly_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();
					$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($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($last_payroll_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',PHPExcel_Shared_Date::ExcelToPHP($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.'"';
										}	
										// echo "BSK $pick_query <br/>";
										$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){
											// $status_info["$excel_line_value$row"] = "Invalid $get_cell_value";
											$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){
											// $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;
											$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){
									//$status_info[$excel_line_column_name] = $get_cell_value;
									/*if($excel_line_column_name === 'component_value'){
										$component_value = $get_cell_value;
									}*/
									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'];
							$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'];
							$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'];
							$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'];
							$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;
						}
						//UPDATE A SHIFT NAME FOR SAME SHIFT DATE
						// if($insert_info){
						// 	$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,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),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("CALL sp_a_run ('RUN','$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,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($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){
		$prime_financial_id  = $this->leave_financial_info[0]->prime_leave_financial_year_id;
		$starting_date       = date('Y-m-d',strtotime($this->leave_financial_info[0]->starting_date));	
		$ending_date         = date('Y-m-d',strtotime($this->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,auto_prime_id,auto_dispaly_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();
					$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 cw_employees.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_reduce($employees_qry_rslt ?? [], function($result, $arr) {
				    $result[$arr['employee_code']] = $arr;
					    return $result;
					}, array());

					//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_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;		
								}	
							}	
						}
						// $leave_name_balance_used     = rtrim($leave_name_balance_used,",");		
						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_reduce($opening_balance_used_rslt ?? [], function ($result, $arr) {
							    $result[$arr['employee_code']] = $arr;
							    return $result;
							}, array());
						}
						//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());

						//get current financial year details
						$prime_financial_id     =  $this->leave_financial_info[0]->prime_leave_financial_year_id;	
						$starting_date          = date('Y-m-d',strtotime($this->leave_financial_info[0]->starting_date));	
						$ending_date            = date('Y-m-d',strtotime($this->leave_financial_info[0]->ending_date));	
						$error                  = 0;
						// $success_sts     = array();
						for($row =$excel_row_start; $row <= $total_rows; $row++) {
							$prime_column_val             = "";
							$prime_cell_val               = "";
							$exist_val                    = "";
							$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 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($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_status_info['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_status_info['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',PHPExcel_Shared_Date::ExcelToPHP($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_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){
														$err_status_info["$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 Row"] = $row;
												// $err_status_info['status']    = "Invalid $get_cell_value";
												$err_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){
													// $err_status_info["Excel Row"] = $row;
													// $err_status_info['status']    = "Invalid $get_cell_value";
													$err_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){
										//$status_info[$excel_line_column_name] = $get_cell_value;
										/*if($excel_line_column_name === 'component_value'){
											$component_value = $get_cell_value;
										}*/
										if($excel_line_column_name === 'employee_code'){
											// $emp_code_col_name  = $excel_line_value;
											$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'];
											// $emp_resign_date   = $employees_arr[$employee_code]['resignation_date'];

											if(!$employees_arr[$employee_code] || !$category){
												$error         = 1;
												$err_status_info["$excel_line_value$row"] = "Invalid $employee_code Employee code or Category Not Mapped.. Please Check it..!";
												$picklist_sts            = FALSE;
											}else
											if(!$emp_doj){
												$error         = 1;
												$err_status_info["$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($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;
										}

										// echo "excel_line_column_name::$leave_type";
										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)){
												$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 ");
								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 $this->prime_table.leave_status in (1,2)";
									//echo "$exist_query\n";
									$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;

									//DR CODE FOR CHECK EXIST LEVAE ENTRY COUNT
									if(!(int)$exist_count){
										//THIS SELECT QUERY FOR CHECK A SAME LEAVE DATE AND LEVAE DATE TYPE FOR THEN ONLY CHECK A FULL DAY
										$check_leave_val = 'cw_leave_entry.employee_code =  "'.$employee_code.'" and cw_leave_entry.leave_date =  "'.$leave_date.'" and cw_leave_entry.date_type =  "1" and cw_leave_entry.leave_status in (1,2)';

										$exist_query = "select count(*) exist_count,$this->prime_table.trans_status,$this->prime_table.$prime_id from $this->prime_table where $check_leave_val";

									//echo "$exist_query\n";
									$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($leave_date && $emp_doj){
								if($emp_doj > $leave_date){
									$error         = 1;
									$err_status_info["$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),";

									//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'];
										$leave_type    = $leave_creation_arr[$leave_type]['leave_name'];

										if($employee_code && $category){
											//function for get a MONTH DAY RELATED INFORMATION
											$month_day_info    =  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_status_info["$row"] = "$employee_code in Leave Balance Not Avialable 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'];

											//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 = "'.$leave_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();

											// if(count($time_entry_rslt[0])){
												$prime_time_id      = $time_entry_rslt[0]['prime_time_entry_id'];
												// $punch_in           = $time_entry_rslt[0]['punch_in'];
												// $punch_out          = $time_entry_rslt[0]['punch_out'];
												// $manual_in          = $time_entry_rslt[0]['manual_in'];
												// $manual_out         = $time_entry_rslt[0]['manual_out'];
												$entry_flag         = $time_entry_rslt[0]['entry_flag'];
												$first_half_status  = $time_entry_rslt[0]['first_half_status'];
												$first_half_count   = $time_entry_rslt[0]['first_half_count'];
												$second_half_status = $time_entry_rslt[0]['second_half_status'];
												$second_half_count  = $time_entry_rslt[0]['second_half_count'];

												$day_type           = $time_entry_rslt[0]['whole_day_status'];
												$check_day_type     = (int)$day_status_legend_arr[$day_type]['day_type'];
											// }
											
											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         = "L";
													    // $update_flag        = "L";
														$whole_day_status   = "L";
														$first_half_status  = strtoupper($leave_type);
														$second_half_status = strtoupper($leave_type);
														$first_half_count   = 0.5;
														$second_half_count  = 0.5;
													}else
													if($date_type === 2){
														if($day_type === "W"){
															// if($entry_flag !== ""){
																$update_flag  = "W";
															// }
															$entry_flag         = "L";
															$first_half_status  = strtoupper($leave_type);
															$whole_day_status   = "$entry_flag"."$update_flag";
															$first_half_count   = 0.5;
														}else
														if($day_type === "U"){
															// if($entry_flag !== ""){
																$update_flag  = "U";
															// }
															$entry_flag         = "L";
															$first_half_status  = strtoupper($leave_type);
															$whole_day_status   = "$entry_flag"."$update_flag";
															$first_half_count   = 0.5;
														}
													}else
													if($date_type === 3){
														if($day_type === "W"){
															// if($entry_flag !== ""){
																$update_flag  = "W";
															// }
															$entry_flag         = "L";
															$second_half_status = strtoupper($leave_type);
															$whole_day_status   = "$update_flag"."$entry_flag";
															$second_half_count  = 0.5;
														}else
														if($day_type === "U"){
															// if($entry_flag !== ""){
																$update_flag  = "U";
															// }
															$entry_flag         = "L";
															$second_half_status = strtoupper($leave_type);
															$whole_day_status   = "$update_flag"."$entry_flag";
															$second_half_count  = 0.5;
														}
													}
													// else{
													// 	$status = "false";
													// 	break;
													// }
													//UPD QUERY VALUE
													$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_master_id.'","'.$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){
												$error = 1;
												$err_status_info["$row"] = "Already Exist in Attendance Entry";
											}else
											if(($check_day_type !== $date_type) && $entry_flag){
												if($date_type === 1){
													$error = 1;
													$err_status_info["$row"] = "Already Exist in Attendance Entry";
												}else{
													$update_flag  = "L";
													//for 1st half update
													if($check_day_type === 3){
														if($date_type === 2){
															$first_half_status  = strtoupper($leave_type);
															$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 = strtoupper($leave_type);
															$whole_day_status   = "$entry_flag"."$update_flag";
															$second_half_count  = 0.5;
														}
													}

													//UPD QUERY VALUE
													$time_entry_upd_value .= '("'.$prime_time_id.'","'.$shift_master_id.'","'.$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     = "L";
												if($date_type === 1){
													$whole_day_status   = "L";
													$first_half_status  = strtoupper($leave_type);
													$second_half_status = strtoupper($leave_type);
			
													$first_half_count   = 0.5;
													$second_half_count  = 0.5;
												}
												else//for 1st half insert
												if($date_type === 2){
													$whole_day_status   = "FL";
													$first_half_status  = strtoupper($leave_type);
													$first_half_count   = 0.5;
													$second_half_status = "";
													$second_half_count  = "";
												}
												else//for 2nd half insert
												if($date_type === 3){
													$whole_day_status   = "SL";
													$second_half_status = strtoupper($leave_type);
													$first_half_status  = "";
													$first_half_count   = "";
													$second_half_count  = 0.5;
												}
													
												//INSERT QUERY VALUE
												$time_entry_ins_value .= '("'.$employee_code.'","'.$shift_master_id.'","'.$leave_date.'","'.$entry_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").'"),';
											}
											$status_info['Status'] = "Inserted to DB";	
											// $status_array[]        = $status_info;				
											
										}
									}	
								}else
								if($picklist_sts){
									$error = 1;
									$err_status_info["$row"] = "Already Exist in DB";
								}

								$status_array[]     = $status_info;
								if(!empty($err_status_info)){
									$err_status_array[] = $err_status_info;
								}
								
							}
						}

						if(!empty($err_status_array)){
							$table_info = $this->get_excel_error_ui($err_status_array);
							return json_encode(array('success'=>false,'message'=>" file not imported",'table_info'=>$table_info));
						}else{
							if((int)$error === 0 && $picklist_sts){
								$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_query          = "insert into $this->prime_table ($prime_column_val) VALUES $prime_query_value";						
										$insert_info          = $this->db->query($prime_query);

										if($insert_info){
											$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,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),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("CALL sp_a_run ('RUN','$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,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){
											// if($time_entry_ins_info){
											if(count($opening_arr ?? [])){
												$this->update_used_leave($opening_arr,$opening_balance_used_arr,$prime_financial_id);
											}
											// }
										}
									}			
									// $status_array[]  = 	$success_sts;
									$table_info = $this->get_excel_import_ui($status_array);
									return json_encode(array('success'=>true,'message'=>"Successfully file 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){
		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,dependent_pick_list,dependent_pick_input,table_column1,date_type,table_column2,label_name,auto_prime_id,auto_dispaly_value,pick_display_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();
					$worksheetTitle  = $sheet->getTitle();
					$check_excel 	 = $this->check_import_error($excel_format_result,$total_rows,$excel_row_start,$sheet);
					$err_column_count = count($check_excel['error'] ?? []);
					if((int)$err_column_count > 0){
						$table_info   = $this->get_excel_error_ui($check_excel);
						echo json_encode(array('success'=>false,'message'=>"Column Wise Error",'table_info'=>$table_info));
						exit(0);
					}
					$excel_label_wise 	= json_decode(json_encode($excel_format_result),true);
					$excel_label_wise  = array_reduce($excel_label_wise ?? [], function($result, $arr){
					    $result[$arr['label_name']] = $arr;
					    return $result;
					}, array());
					$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;
						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;
							$date_type              = (int)$excel_info->date_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;
							$label_name       		= $excel_info->label_name;
							$dependent_pick_list	= (int)$excel_info->dependent_pick_list;
							$get_cell_value         = ucwords(trim($sheet->getCell("$excel_line_value$row")->getValue()));
							
                            if($get_cell_value){
								// FOR DATE
								if($field_type === 4){
									if($date_type === 1){
										$get_cell_value = trim(Date::excelToDateTimeObject($sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));
									}else
									if($date_type === 2){
										// $cellFormat = $sheet->getStyle($excel_line_value)->getNumberFormat()->getFormatCode();
										$get_cell_value = trim(Date::excelToDateTimeObject($sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m'));
									}
								}else
								if($field_type === 13){
									$get_cell_value = trim(date('Y-m-d H:i:s',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getValue())));
								}else
								// FOR PICKLIST CHECK
								if(($field_type === 5) || ($field_type === 7) || ($field_type === 9)){
									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.'"';
										// 
										$depen_whr_join = "";
										$depen_inner_join = "";
										if((int)$dependent_pick_list === 1){
											$dependent_pick_input = $excel_info->dependent_pick_input;
											$depend_input  		= $excel_label_wise[$label_name]['dependent_pick_input'];
											$depend_line_val  	= $excel_label_wise[$depend_input]['excel_line_value'];

											$depen_cell_value         = ucwords(trim($sheet->getCell("$depend_line_val$row")->getValue()));

											if((int)$field_type === 9){
												$depen_auto_prime_id = $excel_label_wise[$depend_input]['auto_dispaly_value'];
												$depen_pick_tbl = $excel_label_wise[$depend_input]['pick_table'];
												$depen_tbl1 = $excel_info->table_column1;
												$depen_tbl2 = $excel_info->table_column2;
												$depen_inner_join	= ' inner join '.$depen_pick_tbl.' on '.$depen_pick_tbl.'.'.$depen_tbl1.' = '.$pick_table.'.'.$depen_tbl2.'';
												$depen_whr_join	= ' and '.$depen_pick_tbl.'.'.$depen_auto_prime_id.' = "'.$depen_cell_value.'"';
											}else
											if(($field_type === 5) || ($field_type === 7)){
												$depen_pick_import = $excel_label_wise[$depend_input]['pick_list_import'];
												$depen_pick_tbl = $excel_label_wise[$depend_input]['pick_table'];
												$depen_pick_list_val = $excel_label_wise[$depend_input]['pick_list'];
												$depen_tbl1 = $excel_info->table_column1;
												$depen_tbl2 = $excel_info->table_column2;
												$depen_list_val   = explode(",",$depen_pick_list_val ?? "");
												$depen_pick_val_1 = $depen_list_val[0];
												$depen_pick_val_2 = $depen_list_val[1];
												if((int)$depen_pick_import === 1){
													$depen_whr_join	= ' and '.$depen_pick_tbl.'.'.$depen_pick_val_1.' = "'.$depen_cell_value.'"';
												}else
												if((int)$depen_pick_import === 2){
													$depen_whr_join	= ' and '.$depen_pick_tbl.'.'.$depen_pick_val_2.' = "'.$depen_cell_value.'"';
												}
												$depen_inner_join	= ' inner join '.$depen_pick_tbl.' on '.$depen_pick_tbl.'.'.$depen_tbl1.' = '.$pick_table.'.'.$depen_tbl2.'';
											}
										}
										if($pick_list_import === 1){
											$pick_query = 'select '.$pick_list.' from '.$pick_table.' '.$depen_inner_join.' where '.$pick_list_val_1.' = "'.$get_cell_value.'" '.$depen_whr_join.'';	
										}else{
											$pick_query = 'select '.$pick_list.' from '.$pick_table.' '.$depen_inner_join.' where '.$pick_list_val_2.' = "'.$get_cell_value.'" '.$depen_whr_join.'';
										}
										$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;
											}
										}else
										if((int)$pick_count === 1){
											if($pick_table !== $this->prime_table){
												$pick_id     = $pick_result[0]->$pick_list_val_1;
												$pick_status = $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 = $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){
									$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";
							//echo "$exist_query\n";
							$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){
								$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 '.$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]
									//echo "$upd_query\n";
									$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
									$status_info['status'] = "<p style='color:#15da15'>Updated Successfully...</p>";
								/*}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));
				}
			}
		}
	}	
		
//LOAN IMPORT DATA AND VALIDATION PARTS START
	public function do_loan_excel_import($import_id){
		$created_on = date("Y-m-d H:i:s");
		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,auto_prime_id,auto_dispaly_value,date_type,text_type 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();
					}
					$logged_area_access_arr = explode(',', $this->logged_area_access ?? "");

					//LOAN DATA VALIDATION MANDATORY FILED AND 
					$err_column_array    = array();
					$err_column_tabview  = array();
					$err_status_array	 = array();
					$emp_cat_arr         = array();
					for($row = $excel_row_start; $row <= $total_rows; $row++) {
						$err_sts         = 0;
						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;
							$mandatory_field        = (int)$excel_info->mandatory_field;
							$date_type              = (int)$excel_info->date_type;
							$text_type              = (int)$excel_info->text_type;
							$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;

							$get_cell_value         = trim($sheet->getCell("$excel_line_value$row")->getCalculatedValue());

							if(empty($get_cell_value) && $excel_line_column_name !== "interest_rate"){
								$err_column_array['error']["$excel_line_value$row"] = $view_name;
								$msg_line   = ": Empty Field - Column cannot be left empty..!";
								$err_column_tabview['error']["$excel_line_value$row"]  = $view_name." ".$msg_line;
								$err_sts    = 1; 
							}else
							if($field_type === 4){//FOR DATE VALIDATE
								$excel_date = trim(Date::excelToDateTimeObject($sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));	
								if($excel_date === "1900-01-01"){
									$err_column_array['error']["$excel_line_value$row"] = $view_name;
										$msg_line   = "Please enter valid date... Please map The Date Format Like (DD/MM/YYYY)";
										$err_column_tabview['error']["$excel_line_value$row"]  = $view_name." ".$msg_line;
										$err_sts    = 1; 
								}else{
									if($excel_line_column_name === "loan_date"){
										$loan_date       = "";
										$loan_date_value = "";
										if(!empty($get_cell_value)){
											$loan_cell_value = trim(Date::excelToDateTimeObject($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 = trim(Date::excelToDateTimeObject($sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m'));
										}
									}
								}
							}
							else
							if((int)$field_type === 5 || (int)$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.'"';
									}
									
									$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"] = $view_name;
										$msg_line   = "Invalid Data is Present Please Check it.!";
										$err_column_tabview['error']["$excel_line_value$row"]  = $view_name." ".$msg_line;
										$err_sts    = 1; 
									}
								}
							}
							elseif($field_type === 1 ){
								if($text_type === 1){   //TEXT
									if(!empty($get_cell_value)){
										if (!ctype_alpha($get_cell_value) ) {
											$err_column_array['error']["$excel_line_value$row"] = $view_name;
											$msg_line = ": Invalid - Please provide valid Text.!";
											$err_column_tabview['error']["$excel_line_value$row"]  = $view_name." ".$msg_line;
										}
									}
								}else
								// if($text_type === 2){  //TEXT & ALPHA
								// 	if(!empty($get_cell_value)){
								// 		if ((int)$this->validateString($get_cell_value) === 0) {
								// 			$err_column_array['error']["$excel_line_value$row"] = $view_name;
								// 			$msg_line = ": Invalid - Please use correct Numeric and Text format.! ";
								// 			$err_column_tabview['error']["$excel_line_value$row"]  = $view_name." ".$msg_line;
								// 		}
								// 	}
								// }else
								if($text_type === 3){  //INTEGER
									if(!empty($get_cell_value)){
										if(!filter_var($get_cell_value, FILTER_VALIDATE_INT)) {
											$err_column_array['error']["$excel_line_value$row"] = $view_name;
											$msg_line = ": Invalid - Please provide a valid integer.!";
											$err_column_tabview['error']["$excel_line_value$row"]  = $view_name." ".$msg_line;
										}
									}
								}
								if($excel_line_column_name === "apply_year"){
									$apply_cell_value       = "";
									if(!empty($get_cell_value)){
										$excel_date = trim(Date::excelToDateTimeObject($sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));	
										if($excel_date === "1900-01-01"){
											$err_column_array['error']["$excel_line_value$row"] = $view_name;
											$msg_line    = "Please Enter Valid Month & Year ... Please map The Date Format Like (MM/YYYY)";
											$err_column_tabview['error']["$excel_line_value$row"]  = $view_name." ".$msg_line;
											$err_sts     = 1; 
										}else{
											$apply_month_line_val   = $excel_info->excel_line_value;
											$apply_month_view_name  = $view_name;
											$apply_cell_value       = trim(Date::excelToDateTimeObject($sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m'));
										}
									}
								}
							}elseif ($field_type === 4){  	// FOR DATE		
								$cell = $sheet->getCell("$excel_line_value$row");
								$excelDateValue = $cell->getValue(); 
								$dateObj = Date::excelToDateTimeObject($excelDateValue); // Convert the raw date value to a PHP date object
								$formattedDate = $dateObj->format('d-m-Y');
								if($date_type === 1){  //DATE-MONTH-YEAR									
									if(!empty($formattedDate)){
										if((int)$this->validateDOB($formattedDate) === 0) {
											$err_column_array['error']["$excel_line_value$row"] = $view_name;
											$msg_line = ": Invalid - Please use the correct Date format (DD-MM-YYYY).!";
											$err_column_tabview['error']["$excel_line_value$row"] = $view_name." ".$msg_line;
										}
									}
								}else
								if($date_type === 3){  //YEAR
									if(!empty($excelDateValue)){
										if ((int)$this->validateYear($excelDateValue) === 0) {
											$err_column_array['error']["$excel_line_value$row"] = $view_name;
											$msg_line = ": Invalid - Please use the correct YEAR format (YYYY).!";
											$err_column_tabview['error']["$excel_line_value$row"] = $view_name." ".$msg_line;
										}
									}
								}else
								if($date_type === 2){  //MONTH-YEAR
									if(!empty($excelDateValue)){
										if ((int)$this->validateMonthYear($excelDateValue) === 0) {
											$err_column_array['error']["$excel_line_value$row"] = $view_name;
											$msg_line = ": Invalid -  Please use the correct MONTH-YEAR format (MM-YYYY).!";
											$err_column_tabview['error']["$excel_line_value$row"] = $view_name." ".$msg_line;
										}
									}
								}
							}
							elseif ($field_type === 8) { //textarea
   								if (!empty($get_cell_value)) {
   									if ((int)$this->validatetextarea($get_cell_value) === 0) {
            							$err_column_array['error']["$excel_line_value$row"] = $view_name;
            							$msg_line = ": Invalid - special characters not permitted.!";
            							$err_column_tabview['error']["$excel_line_value$row"] = $view_name . " " . $msg_line;
							        }
							    }
							}
							else{
								//EMPLOYEE CODE BASED VALIDATIONS CHECK
								if($excel_line_column_name === "employee_code"){									
									$emp_code        = $get_cell_value;
									$emp_line_val    = $excel_info->excel_line_value;
									$emp_view_name   = $view_name;
									$check_emp_qry   = 'select role,date_of_joining,personal_code from cw_employees where trans_status = 1 and employee_code = "'.$emp_code.'" and termination_status = 0';
									$check_emp_data  = $this->db->query("CALL sp_a_run ('SELECT','$check_emp_qry')");
									$check_emp_rslt  = $check_emp_data->result();
									$check_emp_data->next_result();
									// $loan_emp_code_arr[$emp_code] = $emp_code;
									if(empty($check_emp_rslt)){
										$err_column_array['error']["$excel_line_value$row"] = $emp_view_name;
										$msg_line           = "Inactive or Invalid Employee Code $emp_code - Please verify the employee Master.";
										$err_column_tabview['error']["$excel_line_value$row"] = $msg_line;
										$err_status_array[] = "$excel_line_value$row";
										$err_sts            = 1; 
									}else{
										$role                = $check_emp_rslt[0]->role;
										$doj_date            = $check_emp_rslt[0]->date_of_joining;
										$personal_code       = $check_emp_rslt[0]->personal_code;
										if(!$role){
											$err_column_array['error']["$excel_line_value$row"] = $emp_view_name;
											$msg_line           = "Category for Employee Code $emp_code is empty.Please verify the Employee Master.!";
											$err_column_tabview['error']["$excel_line_value$row"] = $msg_line;
											$err_status_array[] = "$excel_line_value$row";
											$err_sts            = 1; 
										}else{
											$emp_cat_arr[$emp_code] = $role;
										}
										if(!$doj_date){
											$err_column_array['error']["$excel_line_value$row"] = $emp_view_name;
											$msg_line           = "Date of Joining for Employee Code $emp_code is empty.Please verify the Employee Master.!";
											$err_column_tabview['error']["$excel_line_value$row"] = $msg_line;
											$err_status_array[] = "$excel_line_value$row";
											$err_sts            = 1; 
										}else{
											$doj_date    = strtotime($doj_date);
										}
										if($personal_code){
											if(!in_array($personal_code,$logged_area_access_arr)){
												$err_column_array['error']["$excel_line_value$row"] = $emp_view_name;
												$msg_line           = "This Employee($emp_code) Not Accessible for your Area Access.!";
												$err_column_tabview['error']["$excel_line_value$row"] = $msg_line;
												$err_status_array[] = "$excel_line_value$row";
												$err_sts            = 1; 
											}
										}
									}
								}
							}
							if($excel_line_column_name === "loan_date"){								
								if($loan_emp_code_arr[$emp_code][$loan_cell_value]){
									$err_column_array['error']["$excel_line_value$row"] = $emp_view_name;
									$msg_line           = "Employee Code $emp_code - Already Exist in Excel,Please check!.";
									$err_column_tabview['error']["$excel_line_value$row"] = $msg_line;
									$err_status_array[] = "$excel_line_value$row";
									$err_sts            = 1; 
								}
								$loan_emp_code_arr[$emp_code][$loan_cell_value] = $emp_code;
							}
							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       = (int)$get_cell_value;
								$install_line_val    = $excel_info->excel_line_value;
								$install_view_name   = $view_name;
								if($no_of_install < 1 || $no_of_install > 99){
									$err_column_array['error']["$excel_line_value$row"] = $view_name;
									$msg_line           = "No of Installment : Out of Range - Only values between 1 and 99 are allowed.!";
									$err_column_tabview['error']["$excel_line_value$row"] = $msg_line;
									$err_status_array[] = "$excel_line_value$row";
									$err_sts            = 1; 
								}
							}
							
							if($excel_line_column_name === "per_month"){
								$per_month            = $get_cell_value;
								$per_month            = (float)number_format((float)$per_month, 2, '.', '');
								$per_month_line_val   = $excel_info->excel_line_value;
								$per_month_view_name  = $view_name;
							}

							if($excel_line_column_name === "total_amount"){
								$total_amount         = $get_cell_value;
								$total_amount         = (float)number_format((float)$total_amount, 2, '.', '');
								$total_amt_line_val   = $excel_info->excel_line_value;
								$total_amt_view_name  = $view_name;
							}

						}
						//validation check only if all above conditions are correct
						// $empty_err_check = $err_column_array['error']["$excel_line_value$row"];
						// if(!$empty_err_check) {
						if(!$err_sts) {
							if($loan_date){
								if($loan_date < $doj_date){
									$err_column_array['error']["$loan_line_val$row"] = $loan_view_name;
									$msg_line = "Loan Date : Invalid - It should not be earlier than the Date of Joining.!";
									$err_column_tabview['error']["$loan_line_val$row"] = $msg_line;
									$err_status_array[] = "$excel_line_value$row";
								}
							}

							if($loan_amount && $no_of_install && $per_month && $total_amount){
								$per_month_val   = $loan_amount / $no_of_install;
								$per_month_val   = (float)number_format((float)$per_month_val, 2, '.', '');
								$tot_amt_val     = $no_of_install * $per_month;
								$tot_amt_val     = (float)number_format((float)$tot_amt_val, 2, '.', '');

								if($per_month !== $per_month_val){
									$err_column_array['error']["$per_month_line_val$row"] = $per_month_view_name;
									$msg_line = "Per Month Value : Invalid - Please Check Loan Amount and Installment.!";
									$err_column_tabview['error']["$per_month_line_val$row"] = $msg_line;
									$err_status_array[] = "$excel_line_value$row";
								}

								if($tot_amt_val !== $total_amount){
									$err_column_array['error']["$total_amt_line_val$row"] = $total_amt_view_name;
									$msg_line = "Total Amount : Invalid - Please Check the Total Amount .!";
									$err_column_tabview['error']["$total_amt_line_val$row"] = $msg_line;
									$err_status_array[] = "$excel_line_value$row";
								}
							}

							if($loan_date_value){								
								// $loan_date_qry    = 'select count(prime_transactions_fms_id) as rslt_count from cw_transactions_fms where trans_status = 1 and date_format(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y") , "%Y-%m") >= date_format(str_to_date("'.$loan_date_value.'", "%m-%Y"), "%Y-%m") and employee_code = "'.$emp_code.'"';
								$loan_date_qry     = 'SELECT COUNT(prime_loan_id) AS loan_count FROM cw_loan WHERE employee_code = "'.$emp_code.'" and loan_date = "'.$loan_cell_value.'"  AND trans_status = 1';
								$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       = (int)$loan_data_result[0]->loan_count;

								if((int)$loan_count > 0){
									$err_column_array['error']["$loan_line_val$row"] = $loan_view_name;
									$msg_line = " - Loan Already exist for this loan date..! ";
									$err_column_tabview['error']["$loan_line_val$row"]  = $loan_view_name.$msg_line;
									$err_status_array[] = "$excel_line_value$row";
								}
							}							
							if($apply_cell_value){
								$app_month_year  = date("Y-m",strtotime($excel_date));
								$loan_date_year  = date("Y-m",strtotime($loan_cell_value));
								if($app_month_year < $loan_date_year){
									$err_column_array['error']["$apply_month_line_val$row"] = $apply_month_view_name;
									$msg_line = "- not less than Loan Date...! ";
									$err_column_tabview['error']["$apply_month_line_val$row"]  = $apply_month_view_name.$msg_line.".!";
									$err_status_array[] = "$excel_line_value$row";
								}

								
								if((int)$no_of_install === 1){
									$where_cond   = ' and transactions_month="'.$apply_cell_value.'"';
								}else{
									$where_cond   = ' and date_format(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y") , "%Y-%m") >= date_format(str_to_date("01-'.$apply_cell_value.'", "%d-%m-%Y"), "%Y-%m")';
								}
								$apply_date_qry    = 'select count(prime_transactions_fms_id) as rslt_count from cw_transactions_fms where trans_status = 1  and employee_code = "'.$emp_code.'" '.$where_cond.'';
								$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       = (int)$apply_data_result[0]->rslt_count;
								if($apply_count !== 0){
									// echo "apply_count => $apply_count";
									$err_column_array['error']["$apply_month_line_val$row"] = $apply_month_view_name;
									$msg_line = "- Your payroll has already been processed.! ";
									$err_column_tabview['error']["$apply_month_line_val$row"]  = $apply_month_view_name.$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) {
						$sts = true;
						$msg = "$err_column $msg_line";
						$table_info = $this->get_excel_error_ui($err_column_tabview);
						echo json_encode(array('success'=>false,'message'=>"File not Imported.!",'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   = "";
						$cf_column_val    = "";
						$cf_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;
							$pick_list_import       = (int)$excel_info->pick_list_import;
							$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());
							//DATE FIELD
							if($field_type === 4){
								$get_cell_value = trim(Date::excelToDateTimeObject($sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));
							}else//PICKLIST FIELD
							if($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.'"';
								if($pick_list_import === 1){
									$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_1.' = "'.$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){
									$pick_id        = $pick_result[0]->$pick_list_val_1;
									$pick_status    = (int)$pick_result[0]->trans_status;
									$get_cell_value = $pick_id;
								}
							}else
							if($excel_line_column_name === "apply_year"){
								$get_cell_value    = trim(Date::excelToDateTimeObject($sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m'));
							}
							if($excel_line_column_name === "employee_code"){
								$cat_id            = $emp_cat_arr[$get_cell_value];
								if($cat_id){
									$prime_column_val .= "category,";
									$prime_cell_val   .= '"' .$cat_id.'",';
								}
							}
							if($field_isdefault === 1){
								$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($prime_column_val){
							// $prime_id    = "prime_".$module_id."_id";
							// $exist_val   = rtrim($exist_val," and ");
							// $exist_query = "select count(*) exist_count from cw_loan_installment where cw_loan_installment.trans_status = 1 and cw_loan_installment.paid_status NOT IN (1,3) 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){
								$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;
								$loan_id           = $insert_id;
								$status_info['Status'] = "Inserted to DB";
								$this->installment_save($loan_id);
								$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 = "";		
		$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 $err_column){
			foreach($err_column as $key => $value){
				$tr_line .= "<tr><td>$key</td><td style='color:#ff0303 !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;
	}*/
	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>$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;
	}
	
	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        = $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 ?? "");
				$table_name_list   = explode(",",$format_rslt[0]->excel_table_name ?? "");
				$excel_format_qry 	= 'select view_name,input_view_type,duplicate_data,picklist_data,field_type,text_type,pick_table,pick_list_type,pick_list_import,pick_list,mandatory_field,field_isdefault,excel_line_column_name,excel_line_value,date_type,unique_field,label_name,dependent_pick_list,dependent_pick_input,table_column1,table_column2,prime_module_id,pick_display_value,auto_prime_id,auto_dispaly_value,field_length 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_info        = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
				$excel_format_result = $excel_format_info->result();
				$excel_format_info->next_result();

				$unq_qry 	= 'select smart_field_name from cw_sap_employee_validation where sap_unique = "Y" and cw_sap_employee_validation.trans_status = 1';
				$unq        = $this->db->query("CALL sp_a_run ('SELECT','$unq_qry')");
				$unq_result = $unq->result();
				$unq->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();	
					//FUNCTION FOR SITE TRANSFER
					if((int)$excel_format === 3){
						$this->emp_site_transfer_import($sheet,$excel_format_result,$excel_row_start,$total_rows);
						
					}else //FUNCTION FOR LEFT EMPLOYEES AMENDMENT
					if((int)$excel_format === 15){
						$this->emp_resignation_import($sheet,$excel_format_result,$excel_row_start,$total_rows);
					}else{
						//Columnwise
						$columnwise_result   = $this->emp_excel_columnwise_checking($excel_format,$sheet,$excel_obj,$import_type,$excel_format_result,$excel_row_start,$total_rows,$module_id,$unq_result);
						
						$err_column_array    = $columnwise_result['err_column_array'];
						$err_column_tabview  = $columnwise_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'=>"Column Wise Error",'table_info'=>$table_info));
							exit();
						}else{
							//Rowwise
							$rowwise_result   = $this->emp_excel_rowwise_checking($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{
								$check_import = $this->check_import_error($excel_format_result,$total_rows,$excel_row_start,$sheet);
								$err_column_count = count($check_import['error'] ?? []);
								if((int)$err_column_count > 0){
									$table_info   = $this->get_excel_error_ui($check_import);
									echo json_encode(array('success'=>false,'message'=>"Column Wise Error",'table_info'=>$table_info));
									exit(0);
								}
								$final_result   = $this->emp_final_excel_import($module_id,$sheet,$import_type,$excel_format_result,$excel_row_start,$total_rows,$exist_column_name);
							}
						}
					}	
				}
			}
		}	
	}
	
function filterArray($value){
	return ($value == 2);
}

//FUNCTION FOR EMPLOYEE MASTER SITE TRANSFER IMPORT(AMENDMENT)
public function emp_site_transfer_import($sheet,$excel_format_result,$excel_row_start,$total_rows){
	$active_emp_qry   = 'select employee_code,emp_name,prime_employees_id,wbs_element,position,termination_status from cw_employees where find_in_set(personal_code,"'.$this->logged_area_access.'")';
	$emp_info         = $this->db->query("CALL sp_a_run ('SELECT','$active_emp_qry')");
	$emp_rslt         = $emp_info->result();
	$emp_info->next_result();
	foreach($emp_rslt as $key => $value){
		if((int)$value->termination_status === 1){
			$inactive_emp_arr[$value->employee_code]=$value->prime_employees_id;
			
		}else{
			$emp_data_rslt[$value->employee_code][$value->wbs_element][$value->position]= $value->prime_employees_id;
			$active_employees[$value->employee_code]=$value->prime_employees_id;
		}	
		$emp_name_arr[$value->employee_code] = $value;	
	}
	// and find_in_set(personal_code,"'.$this->logged_area_access.'")
	$sel_pay_struct_qry   = 'select wbs_element,position from cw_pay_structure where status=1';
	$ps_info              = $this->db->query("CALL sp_a_run ('SELECT','$sel_pay_struct_qry')");
	$ps_rslt              = $ps_info->result_array();
	$ps_info->next_result();

	//readonly based validation
	$readonly_col_qry   = 'select input_columns from cw_role_base_condition where role_module_id="employees" AND FIND_IN_SET("'.$this->logged_user_role.'", role_condition_for)';
	$readonly_col_data   = $this->db->query("CALL sp_a_run ('SELECT','$readonly_col_qry')");
	$read_only_rslt      = $readonly_col_data->result();
	$readonly_col_data->next_result();
	$readonly_columns    = explode(",",$read_only_rslt[0]->input_columns ?? "");

	$pay_struct_arr       = array();
	foreach($ps_rslt as $arr){
		$pay_struct_arr[$arr['wbs_element']][$arr['position']] = $arr;
	}	
	$created_on          = date("Y-m-d H:i:s");
	$upd_emp_code        = array();
	$err_column_array    = array();
	$err_column_tabview  = array();
	$status_array	     = array();
	for($row = $excel_row_start; $row <= $total_rows; $row++) {
		$status_info              = array();	
		$status_info["Excel Row"] = $row;
		foreach($excel_format_result as $excel_info){
			$view_name              = $excel_info->view_name;
			$excel_line_column_name = $excel_info->excel_line_column_name;
			$excel_line_value       = $excel_info->excel_line_value;
			$get_cell_value         = trim(iconv("UTF-8","ISO-8859-1",$sheet->getCell("$excel_line_value$row")->getCalculatedValue())," \t\n\r\0\x0B\xA0");
			if(!$get_cell_value){
				$err_column_array['error']["$excel_line_value$row"] = $view_name;
				$msg_line = "Invalid - Empty Columns - Please verify the data..!";
				$err_column_tabview['error']["$excel_line_value$row"]  = $msg_line;
			}else{
				if($excel_line_column_name === "employee_code"){
					$emp_log[$excel_line_column_name] = $get_cell_value;
					$employee_code    = $get_cell_value;
					$prime_emp_id     = $active_employees[$employee_code];
					if(in_array($employee_code,$inactive_emp_arr)){
						$err_column_array['error']["$excel_line_value$row"] = $view_name;
						$msg_line = "Inactive Employee Code Please check in Employee master...!";
						$err_column_tabview['error']["$excel_line_value$row"]  = $msg_line;
					}else
					if(!in_array($employee_code,$active_employees) && !array_key_exists($employee_code,$active_employees)){
						$err_column_array['error']["$excel_line_value$row"] = $view_name;
						$msg_line = "Invalid Employee Code";
						$err_column_tabview['error']["$excel_line_value$row"]  = $msg_line;
					}else					
					if($employee_code && !$prime_emp_id){
						$err_column_array['error']["$excel_line_value$row"] = $view_name;
						$msg_line = "Do not have Permission to Update, Please check your Area access...!";
						$err_column_tabview['error']["$excel_line_value$row"]  = $msg_line;
					}else
					if(in_array($employee_code,$upd_emp_code)){
						$err_column_array['error']["$excel_line_value$row"] = $view_name;
						$msg_line = "Duplicate Entry..! Employee Code Already Exist in Excel";
						$err_column_tabview['error']["$excel_line_value$row"]  = $msg_line;
					}
				}else
				if($excel_line_column_name === "wbs_element"){
					$wbs_element   = $get_cell_value;
					$emp_log[$excel_line_column_name] = $get_cell_value;
				}else{
					$position      = $get_cell_value;
					$emp_log[$excel_line_column_name] = $get_cell_value;
				}
				if($excel_line_column_name !== "employee_code"){
					if(in_array($excel_line_column_name,$readonly_columns)){
						$err_column_array['error']["$excel_line_value$row"] = $view_name;
						$msg_line = "is Readonly you don't have permission to update";
						$err_column_tabview['error']["$excel_line_value$row"]  = $view_name." ".$msg_line;
					}
				}	
			}			
		}
		
		if($wbs_element && $position){
			if(!$pay_struct_arr[$wbs_element][$position]){
				$err_column_array['error']["$excel_line_value$row"] = $view_name;
				$msg_line = "Pay Structure Not Exist for this Wbs and Position";
				$err_column_tabview['error']["$excel_line_value$row"]  = $msg_line;
			}else
			if($emp_data_rslt[$employee_code][$wbs_element][$position]){
				$err_column_array['error']["$excel_line_value$row"] = $view_name;
				$msg_line = "Same Wbs and Position already exist in this Employee...!";
				$err_column_tabview['error']["$excel_line_value$row"]  = $msg_line;
			}
		}	
		$err_count = count($err_column_array['error'] ?? []);
		if($err_count <= 0){
			$wbs_position_update  .= '("'.$prime_emp_id.'","'.$wbs_element.'","'.$position.'","'.$this->logged_id.'","'.$created_on.'"),';
			$status_info['Status'] = "Updated to DB";
			$status_array[]        = $status_info;
		}
		$upd_emp_code[$employee_code]    = $employee_code;
		
	}
	$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();
	}else{
		//function for insert employee log table
		$emp_log['emp_name'] = $emp_name_arr[$employee_code]->emp_name;
		$this->employee_log($prime_emp_id,$emp_log);
		if($upd_emp_code){
			//update wbs,position in employee master
			$wbs_position_update  = rtrim($wbs_position_update,",");
			$emp_wbs_pos_upd     = 'INSERT INTO cw_employees (prime_employees_id,wbs_element,position,trans_updated_by,trans_updated_date) VALUES '.$wbs_position_update.' ON DUPLICATE KEY UPDATE wbs_element = VALUES(wbs_element),position = VALUES(position),trans_updated_by = VALUES(trans_updated_by),trans_updated_date = VALUES(trans_updated_date)';
			$emp_wbs_pos_upd_info    = $this->db->query("CALL sp_a_run ('RUN','$emp_wbs_pos_upd')");

			//update paystructure combination in employee master based on (wbs and position)
			$emp_codes       = '"'.implode('","',$upd_emp_code ?? []).'"';
			$emp_update_qry    ='UPDATE cw_employees INNER JOIN cw_pay_structure ON (cw_pay_structure.wbs_element = cw_employees.wbs_element AND cw_pay_structure.position = cw_employees.position AND STATUS = 1) INNER JOIN cw_sap_wbs ON cw_sap_wbs.wbs_id = cw_pay_structure.wbs_element SET cw_employees.personal_code = cw_pay_structure.personal_code,cw_employees.project_id = cw_sap_wbs.wbs_project_id,cw_employees.activity_no = cw_pay_structure.activity_no,cw_employees.network_id = cw_sap_wbs.wbs_network_id,cw_employees.role = cw_pay_structure.category,cw_employees.professional_tax_location = cw_pay_structure.tax_location WHERE cw_employees.employee_code IN ('.$emp_codes.') AND cw_pay_structure.status = 1 AND cw_pay_structure.trans_status = 1';
			$emp_upd_info      = $this->db->query("CALL sp_a_run ('UPDATE','$emp_update_qry')");
			$msg        = "Successfully files imported in database!!!";
			$table_info = $this->get_excel_import_ui($status_array);
			$status     = true;
		}else{
			$status     = false;
			$msg        = "Files Not imported!!!";
		}
		
	}
	echo json_encode(array('success'=>$status,'message'=>$msg,'table_info'=>$table_info));			
}

//FUNCTION FOR LEFT EMPLOYEES AMENDMENT
public function emp_resignation_import($sheet,$excel_format_result,$excel_row_start,$total_rows){
	$left_qry  = 'select prime_employees_id,emp_name,termination_status,employee_code,date_of_joining from cw_employees where find_in_set(personal_code,"'.$this->logged_area_access.'")';
	$left_info = $this->db->query("CALL sp_a_run ('SELECT','$left_qry')");
	$left_rslt = $left_info->result_array();
	$left_info->next_result();
	$active_emp_arr     = array();
	$in_active_emp_arr  = array();
	foreach($left_rslt as $key => $val){
		if((int)$val['termination_status'] === 1){
			$in_active_emp_arr[$val['employee_code']] = $val;
		}else{
			$active_emp_arr[$val['employee_code']]= $val;
		}
		$emp_name_arr[$val['employee_code']] =$val;
	}
	$emp_code_arr          = array_column($left_rslt,'prime_employees_id','employee_code');
	//readonly based validation
	$readonly_col_qry   = 'select input_columns from cw_role_base_condition where role_module_id="employees" AND FIND_IN_SET("'.$this->logged_user_role.'", role_condition_for)';
	$readonly_col_data   = $this->db->query("CALL sp_a_run ('SELECT','$readonly_col_qry')");
	$read_only_rslt      = $readonly_col_data->result();
	$readonly_col_data->next_result();
	$readonly_columns    = explode(",",$read_only_rslt[0]->input_columns ?? "");

	$seperation_type_qry   = 'SELECT * FROM `cw_zct_12` WHERE cw_zct_12_status=1';//QUERY FOR SEPARATION TYPE
	$seperation_info       = $this->db->query("CALL sp_a_run ('SELECT','$seperation_type_qry')");
	$seperation_rslt       = $seperation_info->result_array();
	$seperation_info->next_result();
	$sep_type_arr          = array_column($seperation_rslt, 'cw_zct_12_id','cw_zct_12_value');
	$err_column_array      = array();
	$err_column_tabview    = array();
	$status_array	       = array();
	$emp_code_check        = array();
	$created_on          = date("Y-m-d H:i:s");
	for($row = $excel_row_start; $row <= $total_rows; $row++) {
		$status_info              = array();	
		$status_info["Excel Row"] = $row;
		foreach($excel_format_result as $excel_info){
			$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              = $excel_info->pick_list;
			$pick_table             = $excel_info->pick_table;			
			$get_cell_value		    = trim(iconv("UTF-8","ISO-8859-1",$sheet->getCell("$excel_line_value$row")->getCalculatedValue())," \t\n\r\0\x0B\xA0");
			if($excel_line_column_name === "employee_code"){
				$employee_code    = $get_cell_value;
				$prime_emp_id     = $emp_code_arr[$employee_code];
				$doj              = $active_emp_arr[$employee_code]['date_of_joining'];	
				$message          = "";
				$emp_log["employee_code"] = $employee_code;
				if($employee_code && !$prime_emp_id){
					$err_column_array['error']["$excel_line_value$row"] = $view_name;
					$msg_line   = "Your don't have permission to update, please check area access..!";
					$err_column_tabview['error']["$excel_line_value$row"]  = $msg_line;
				}
				if(!$emp_code_arr[$employee_code]){ 
					$err_column_array['error']["$excel_line_value$row"] = $view_name;
					$msg_line   = "Invalid Employee Code, Please check...!";
					$err_column_tabview['error']["$excel_line_value$row"]  = $msg_line;
				}
				if(in_array($employee_code,$emp_code_check)){ //EXCEL DUPLICATE ENTRY CHECK
					$err_column_array['error']["$excel_line_value$row"] = $view_name;
					$msg_line   = "Duplicate Entry..! Employee Code Already Exist in Excel";
					$err_column_tabview['error']["$excel_line_value$row"]  = $msg_line;
				}
				if(!$employee_code){ //EMPTY DATA
					$err_column_array['error']["$excel_line_value$row"] = $view_name;
					$msg_line   = "Empty Columns - Please verify the data..!";
					$err_column_tabview['error']["$excel_line_value$row"]  = $msg_line;
				}					
			}else			
			if($excel_line_column_name === "resignation_date"){    			
				$cell = $sheet->getCell("$excel_line_value$row");
				$excelDateValue = $cell->getValue();
				$resign_date_value     = "";
				if(!empty($excelDateValue) && is_numeric($excelDateValue)){
					$dateObj    = Date::excelToDateTimeObject($excelDateValue);
					$resign_date_value  = $dateObj->format('Y-m-d');
					$resign_line_val    = $excel_info->excel_line_value;
					$resign_view_name   = $view_name;					
				}	
				if($resign_date_value){
					$emp_log[$excel_line_column_name] = $resign_date_value;
				}else{
					$emp_log[$excel_line_column_name] = "0000-00-00";
				}		
			}else
			if($excel_line_column_name === "separation_type"){
				$sep_type        = $get_cell_value;
				if($sep_type){
					$separation_type = $sep_type_arr[$sep_type];
					if(!$separation_type){ //CHECK SEPARATION TYPE
						$err_column_array['error']["$excel_line_value$row"] = $view_name;
						$msg_line   = "Invalid Separation type please Check...!";
						$err_column_tabview['error']["$excel_line_value$row"]  = $msg_line;
					}
					$emp_log[$excel_line_column_name] = $separation_type;
				}else{
					$emp_log[$excel_line_column_name] = "0";
				}
				
				if($employee_code && (!$resign_date_value && !$sep_type)){
					if($active_emp_arr[$employee_code]){
						$msg_line = "Employee Code ($employee_code) already Active Please Check...!";
						$err_column_array['error']["A $row"]   = "Employee Code";
						$err_column_tabview['error']["A $row"] =  $msg_line;
					}
				}
				
			}				
		} 
		if($excel_line_column_name !== "employee_code"){
			if(in_array($excel_line_column_name,$readonly_columns)){
				$err_column_array['error']["$excel_line_value$row"] = $view_name;
				$msg_line = " is Disabled Input.. You don't have a permission to update...!";
				$err_column_tabview['error']["$excel_line_value$row"]  = $view_name." ".$msg_line;
			}
		}		
		if ((empty($resign_date_value) && !empty($sep_type)) || (!empty($resign_date_value) && empty($sep_type))) {
			$err_column_array['error']["$excel_line_value$row"] = $view_name;
			$msg_line   = "Resignation Date And Seperation Type should have a valid record or Empty record...!";
			$err_column_tabview['error']["$excel_line_value$row"]  = $msg_line;
		}
		if($resign_date_value){
			if($resign_date_value < $doj){
				$msg_line = "Not lesser than date of Joining, please Verify the date?.";
				$err_column_array['error']["$excel_line_value$row"]   = "Resignation Date";
				$err_column_tabview['error']["$excel_line_value$row"] = "Resignation Date" . " " . $msg_line;
			}
		}	
		if($employee_code && $separation_type && $resign_date_value){
			if($in_active_emp_arr[$employee_code]){
				$msg_line = "Employee Code ($employee_code) already Inactive Please Check...!";
				$err_column_array['error']["A $row"]   = "Employee Code";
				$err_column_tabview['error']["A $row"] =  $msg_line;
			}
		}	
		$err_count = count($err_column_array['error'] ?? []);
		if($err_count <= 0){
			if(empty($separation_type) && empty($resign_date_value)){
				$termination_status = 0;
				$emp_log['termination_status'] = 0;
			}else{
				$termination_status = 1;
				$emp_log['termination_status'] = 1;
			}
			$emp_log['emp_name'] = $emp_name_arr[$employee_code]['emp_name'];
			//function for insert employee log table
			$this->employee_log($prime_emp_id,$emp_log);
			$this->middleware_update($prime_emp_id,$emp_log,$employee_code);
			$emp_update_value    .= '("'.$prime_emp_id.'","'.$separation_type.'","'.$termination_status.'","'.$resign_date_value.'","'.$this->logged_id.'","'.$created_on.'"),';
			$status_info['Status'] = "Updated to DB";
			$status_array[]        = $status_info;
		}
		$emp_code_check[$employee_code]  = $employee_code;	
	}	
	$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();
	}else{
		$emp_left_sts_upd     = rtrim($emp_update_value,",");
		$emp_left_upd_qry     = 'INSERT INTO cw_employees (prime_employees_id,separation_type,termination_status,resignation_date,trans_updated_by,trans_updated_date) VALUES '.$emp_left_sts_upd.' ON DUPLICATE KEY UPDATE separation_type = VALUES(separation_type),termination_status = VALUES(termination_status),resignation_date = VALUES(resignation_date),trans_updated_by = VALUES(trans_updated_by),trans_updated_date = VALUES(trans_updated_date)';
		$emp_left_upd_qry_info = $this->db->query($emp_left_upd_qry);
		
		$table_info = $this->get_excel_import_ui($status_array);
		$status     = true;
		$msg        = "Successfully updated";
		echo json_encode(array('success'=>$status,'message'=>$msg,'table_info'=>$table_info));	
	}	
}
	
public function emp_excel_columnwise_checking($excel_format,$sheet,$excel_obj,$import_type,$excel_format_result,$excel_row_start,$total_rows,$module_id,$unq_result){
	$emp_code_qry         = 'SELECT employee_code,termination_status FROM cw_employees WHERE trans_status = 1 AND find_in_set(personal_code,"'.$this->logged_area_access.'")';
	$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');

	//READONLY VALIDATION
	$readonly_col_qry     = 'SELECT input_columns FROM cw_role_base_condition WHERE role_module_id = "employees" AND FIND_IN_SET("'.$this->logged_user_role.'", role_condition_for)';
	$readonly_col_data    = $this->db->query("CALL sp_a_run ('SELECT','$readonly_col_qry')");
	$read_only_rslt       = $readonly_col_data->result();
	$readonly_col_data->next_result();
	$readonly_columns     = explode(",",$read_only_rslt[0]->input_columns ?? "");

	//INACTIVE VALIDATION
	$left_qry             = 'SELECT employee_code FROM cw_employees WHERE termination_status = 1';
	$left_info            = $this->db->query("CALL sp_a_run ('SELECT','$left_qry')");
	$left_rslt            = $left_info->result_array();
	$left_info->next_result();
	$ter_emp_code         = array_column($left_rslt, 'employee_code');

	//NEW IMPORT VALIDATION
	$new_qry              = 'SELECT employee_code FROM cw_employees WHERE trans_status = 1';
	$new_info             = $this->db->query("CALL sp_a_run ('SELECT','$new_qry')");
	$new_rslt             = $new_info->result_array();
	$new_info->next_result();
	$new_emp_code         = array_column($new_rslt, 'employee_code');	

	$empty_allow_array    = array("resignation_date","separation_type","last_working_date","hold_reason");
	//START CHECKING		
	if($import_type !== 3){
		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;
			$label_name             = $excel_info->label_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;
			$duplicate_data         = (int)$excel_info->duplicate_data;
			$input_view_type        = (int)$excel_info->input_view_type;
			$pick_list_import       = (int)$excel_info->pick_list_import;
			$date_type       		= (int)$excel_info->date_type;
			$text_type       		= (int)$excel_info->text_type;
			$field_length       	= (int)$excel_info->field_length;
			//Columns Based total array
			$multi_get_cell_value   = $sheet->rangeToArray("$excel_line_value$excel_row_start:$excel_line_value$total_rows", NULL, TRUE, TRUE, TRUE);
			//Mandatory fields and popup data validation
			if($mandatory_field === 1){
				$i = $excel_row_start;
				foreach($multi_get_cell_value as $arr_value){
					foreach($arr_value as $col_key =>$col_value){
						//INACTIVE EMPLOYEES ERROR DISPLAY BASED ON TERMINATION STATUS ->NB[06-09-23]
						if($excel_line_column_name === "employee_code"){
							$employee_code    = $col_value;
							if((int)$import_type === 1 && in_array($employee_code,$new_emp_code)){
								$err_column_array['error']["$excel_line_value$i"]    = $view_name;
								$msg_line     = "Invalid - [$employee_code] is already exist..!";
								$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
							}
							if(in_array($employee_code,$ter_emp_code) && (int)$excel_format !== 18){
								$err_column_array['error']["$excel_line_value$i"]    = $view_name;
								$msg_line     = "Invalid - $employee_code is currently marked as inactive..!";
								$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
							}
						}
						//READONLY INPUTS -> DONT HAVE TO UPDATE IN IMPORT EXCEL
						if((int)$import_type === 2){
							if($excel_line_column_name !== "employee_code" && $readonly_columns){
								if(in_array($excel_line_column_name,$readonly_columns)){
									$err_column_array['error']["$excel_line_value$i"] = $view_name;
									$msg_line = "is Readonly you don't have permission to update";
									$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
								}
							}						
						}						
						//LENGTH VALIDATION ROW WISE BASED ON FIELD LENGTH -> NB[31-08-23]
						if($field_type === 1){
							$validation_val  = $col_value;
							if($text_type === 1 || $text_type === 2 || $text_type === 3){
								if($excel_line_column_name !== 'employee_code'){  //LENGTH VALIDATION
									if($validation_val !== "NA" || $validation_val !== "WCI"){
										if(strlen($validation_val) > $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;
										}
									}			
								}
							}
						}
						//DR CODE START FOR AADHAR CARD NO MANDETORY FIELD CHECK EXCEPT EXPAT CATEGORY 
						if(empty($col_value) && !is_numeric($col_value)){
							if(!in_array($excel_line_column_name,$empty_allow_array)){
								$err_column_array['error']["$excel_line_value$i"]   = $view_name;
								$msg_line = ": Invalid - Empty Columns and Invalid Data - Please verify the data..!";
								$err_column_tabview['error']["$excel_line_value$i"] = $view_name." ".$msg_line;
							}		
						}else{
							if($field_type === 1){
								$excel_string = $sheet->getCell("$col_key$i")->getValue();
								if($text_type === 1){   //TEXT
									if(!empty($excel_string)){
										if (!ctype_alpha($excel_string) ) {
											$err_column_array['error']["$excel_line_value$i"] = $view_name;
											$msg_line = ": Invalid - Please provide valid Text.!";
											$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
										}
									}
								}elseif($text_type === 3){  //INTEGER
									if(!empty($excel_string)){
										if(!filter_var($excel_string, FILTER_VALIDATE_INT)) {
											$err_column_array['error']["$excel_line_value$i"] = $view_name;
											$msg_line = ": Invalid - Please provide a valid integer.!";
											$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
										}
									}
								}
							}elseif($field_type === 4){  // FOR DATE		
								$cell           = $sheet->getCell("$col_key$i");
								$excelDateValue = $cell->getValue(); 
								# Convert the raw date value to a PHP date object
								$dateObj        = Date::excelToDateTimeObject($excelDateValue);
								$formattedDate  = $dateObj->format('d-m-Y');
								if($date_type === 1){  //DATE-MONTH-YEAR									
									if(!empty($formattedDate)){
										if((int)$this->validateDOB($formattedDate) === 0){
											$err_column_array['error']["$excel_line_value$i"] = $view_name;
											$msg_line = ": Invalid - Please use the correct Date format (DD-MM-YYYY).!";
											$err_column_tabview['error']["$excel_line_value$i"] = $view_name." ".$msg_line;
										}
									}
								}else
								if($date_type === 2){  //MONTH-YEAR
									if(!empty($excelDateValue)){
										if((int)$this->validateMonthYear($excelDateValue) === 0){
											$err_column_array['error']["$excel_line_value$i"] = $view_name;
											$msg_line = ": Invalid -  Please use the correct MONTH-YEAR format (MM-YYYY).!";
											$err_column_tabview['error']["$excel_line_value$i"] = $view_name." ".$msg_line;
										}
									}
								}else
								if($date_type === 3){  //YEAR
									if(!empty($excelDateValue)){
										if((int)$this->validateYear($excelDateValue) === 0){
											$err_column_array['error']["$excel_line_value$i"] = $view_name;
											$msg_line = ": Invalid - Please use the correct YEAR format (YYYY).!";
											$err_column_tabview['error']["$excel_line_value$i"] = $view_name." ".$msg_line;
										}
									}
								}
							}elseif(($field_type === 5) || ($field_type === 7)){ //PICKLIST
								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_list_where = $pick_list_val_2.' = "'.$col_value.'"';
									if($pick_list_import === 1){
										$pick_list_where = $pick_list_val_1.' = "'.$col_value.'"';
									}
									$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 it.!";
										$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 = $col_value;
												$err_column_array['error']["$excel_line_value$i"] = $view_name;
												$msg_line     = ": Invalid - Range Not Found for $col_value - Please verify the range.";
												$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
											}
										}
									}
								}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 count(*) AS rslt_count 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->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 Data is Present Please Check it.!";
											$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
										}
									}
								}
							}elseif($field_type === 11){
								$length = strlen($col_value);
								if($field_length != strlen($col_value)){
									$err_column_array['error']["$excel_line_value$i"] = $view_name;
									$msg_line = "Invalid - Please provide valid number.!";
									$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
								}
							}elseif($field_type === 12){ //FOR EMAIL
								$email = $col_value;
								if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
									$err_column_array['error']["$excel_line_value$i"] = $view_name;
									$msg_line = ": Invalid - Please provide valid Email.!";
									$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
								}
							}elseif($label_name === 'mobile_number'){ //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 = ": Invalid - Please provide valid Mobile number.!";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}
								}
							}elseif($label_name === 'employee_code'){
								//FOR EMP CODE LENGTH
								if($field_length < strlen($col_value)){
									$err_column_array['error']["$excel_line_value$i"] = $view_name;
									$msg_line = "Employee code is not valid..!";
									$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
								}
							}elseif(((int)$import_type === 2) && ((int)$input_view_type !==3)){
								//amendment checking for duplicate data start
								if($duplicate_data === 1){
									$get_emp_value = array_map('array_filter', $multi_get_cell_value);//empty remove
									$get_emp_value = array_filter($get_emp_value ?? []);
									foreach ($get_emp_value as $current_key => $current_array) {
										foreach ($get_emp_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;
												}
											}
										}
									}
								}
								//amendment checking for invalid emp code
								if($excel_line_column_name === "employee_code"){
									$employee_code = $col_value;
									if(!isset($emp_code_data_result[$col_value])){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
										$msg_line = " is not exit in employee master or personal area is restricted.";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}
									//resigned or not checking MRJ 18APR2020
									if($emp_code_data_result[$col_value] === "1"){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
										$msg_line = " is already resigned, please check it?";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}
								}
							}
						}
						$i++;    
					}
				}
			}elseif(($field_type === 2) || ($field_type === 3)){ 
			//decimal and integer validations for non-mandatory field
				$get_number_value = $sheet->rangeToArray("$excel_line_value$excel_row_start:$excel_line_value$total_rows", NULL, TRUE, TRUE, TRUE);		
				$j = $excel_row_start;
				foreach($get_number_value as $number_valid){
					foreach($number_valid as $num_val){
						if(is_null($num_val)){
							$num_val = 0;
						}
						if(!is_numeric($num_val)){
							$err_column_array['error']["$excel_line_value$j"] = $view_name;
							$msg_line = "column invalid data is present please check it?";
							$err_column_tabview['error']["$excel_line_value$j"]  = $view_name." ".$msg_line;
						//break;
						}
						$j++;
					}
				}
			}
		}	
	}
//END CHECKING
$check_array = array("err_column_array"=>$err_column_array,"err_column_tabview"=>$err_column_tabview);
return $check_array;
}

public function emp_excel_rowwise_checking($sheet,$excel_obj,$import_type,$excel_format_result,$excel_row_start,$total_rows){
	//CHECKING -> WBS AND POSITION AVAILABEL FOR THE EMP CODE OR NOT !!!
	$emp_qry  = 'select wbs_element,position,status,activity_no,category,tax_location from cw_pay_structure where status = 1';
	$emp_info = $this->db->query("CALL sp_a_run ('SELECT','$emp_qry')");
	$emp_rslt = $emp_info->result_array();
	$emp_info->next_result();

	$emp_fil_rslt =array();
	foreach($emp_rslt as $arr){
 		$emp_fil_rslt[$arr['position']][$arr['wbs_element']][$arr['activity_no']][$arr['category']] = $arr['status'];
	}
	//print_r($emp_fil_rslt);
	$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());

	//UNIQUE VALIDATION
	$unique_qry           = 'SELECT smart_field_name FROM cw_sap_employee_validation WHERE trans_status = 1 AND sap_unique = "Y" ' ;
	$unique_info          = $this->db->query("CALL sp_a_run ('SELECT','$unique_qry')");
	$unique_rslt          = $unique_info->result_array();
	$unique_info->next_result();
	$unique_array         = array_column($unique_rslt, 'smart_field_name');
	//print_r($unique_array); die;
	$comp_info            = $this->company_info();
	$minimum_age 	      = $comp_info[0]->minimum_age;
	$maximum_age 	      = $comp_info[0]->maximum_age;	
	$msg_line             = "";
	$sts                  = 1;
	$wbs_element          = "";
	$position             = "";
	$bank_account_num     = "";
	$stop_pay             = "";
	$hold_reason 		  = "";	
	for($row = $excel_row_start; $row <= $total_rows; $row++) {
		$post_data            = array();
		foreach($excel_format_result as $excel_info){
			$field_type             = (int)$excel_info->field_type;
			$text_type              = (int)$excel_info->text_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;
			$field_length       	= (int)$excel_info->field_length;
			$get_cell_value         = trim($sheet->getCell("$excel_line_value$row")->getCalculatedValue());

			//GET 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;
				$post_data['employee_code']  = $employee_code;
			}
			if($excel_line_column_name === "aadhar_card_no"){
				$aadhar_card_no     = $get_cell_value;
				$post_data['aadhar_no']  = $aadhar_card_no;
			}
			//UNIQUE VALIDATION BASED SAP EMP TABLE YES -> NB[22-03-24]
			if(in_array($excel_line_column_name,$unique_array)){
				$post_data[$excel_line_column_name]  = $get_cell_value;
				$post_data['entry_flag']     = "e";				
			}
			if($excel_line_column_name === "stop_pay_code"){
				$stop_pay_query  = 'select prime_status_mode_id from cw_status_mode where status_mode_value = "'.$get_cell_value.'"';
				$stop_pay_data   = $this->db->query("CALL sp_a_run ('SELECT','$stop_pay_query')");
				$stop_pay_result = $stop_pay_data->result();
				$stop_pay_count  = $stop_pay_data->num_rows();
				$stop_pay_data->next_result();
				if((int)$stop_pay_count === 0){
					$err_column_array['error']["$excel_line_value$i"] = $view_name;
					$msg_line    = "Invalid Data is Present Please Check it.!";
					$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
				}else{
					$stop_pay    = $stop_pay_result[0]->prime_status_mode_id;
				}
			}
			if($excel_line_column_name === "hold_reason"){
				$hold_reason 		    = $get_cell_value;
				$hold_line_val          = $excel_info->excel_line_value;
				$hold_view_name         = $view_name;
			}
			if($excel_line_column_name === "date_of_birth"){
				$dob_date = $get_cell_value;
				if(!empty($dob_date)){
					$dob_date_value     = $sheet->getCell("$excel_line_value$row");
					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));
					}else{
						$dob_date_value = trim(Date::excelToDateTimeObject($sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));
					}
					$str_dob            = strtotime($dob_date_value);
					//var years    = parseInt((duration+1)/365);
					if($dob_date_value && $doj_date_value){
						$doj            = strtotime($doj_date_value); // or your date as well
						$dob            = strtotime($dob_date_value);
						$datediff       = $doj - $dob;
						$days           = round($datediff / (60 * 60 * 24));
						$years          = ($days+1)/365;						
					}
					$dob_line_val       = $excel_info->excel_line_value;
					$dob_view_name      = $view_name;
				}
			}	
			if($excel_line_column_name === "wbs_element"){ 
    			$wbs_element            = $get_cell_value;
			} 
			if($excel_line_column_name === "activity_no" && $pick_list_type === 1){ 
    			$activity_no            = $get_cell_value;
				$pick_list_val          = explode(",",$pick_list ?? "");
				$act_list_val_1         = $pick_list_val[0];
				$act_list_val_2         = $pick_list_val[1];
				$act_table              = $pick_table;
			}
			if($excel_line_column_name === "position"){
    			$position               = $get_cell_value;
			}
			if($excel_line_column_name === "bank_account_number"){
				$bank_account_num       = $get_cell_value;
			}
			// FOR CATEGORY
			if($excel_line_column_name === "role" && $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];
				$get_prime_id_qry       = 'SELECT '.$pick_list_val_1.' FROM '.$pick_table.' WHERE '.$pick_list_val_2.' = "'.$get_cell_value.'"';
				$get_prime_id_info      = $this->db->query("CALL sp_a_run ('SELECT','$get_prime_id_qry')");
				$get_prime_id_rslt      = $get_prime_id_info->result();
				$get_prime_id_info->next_result();
				$get_cell_value         = $get_prime_id_rslt[0]->$pick_list_val_1;
				$category               = $get_cell_value;
			}
			// FOR TERMINATION STATUS
			if($excel_line_column_name === "termination_status"){
				$emp_termination_sts    = $get_cell_value;
				$termination_line_val   = $excel_info->excel_line_value;
				$termination_view_name  = $view_name;
			}
			// FOR DATE OF JOINING 
			if($excel_line_column_name === "date_of_joining"){
				$doj_date_value = $sheet->getCell("$excel_line_value$row");
				if((strpos($doj_date_value,"'") || strpos($doj_date_value,'"')) !== false) {
					$doj_date_value = str_replace("'", "", $doj_date_value);
					$doj_date_value = date('Y-m-d', strtotime($doj_date_value));
				}else{
					$doj_date_value = trim(Date::excelToDateTimeObject($sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));
				}				
				$str_doj = strtotime($doj_date_value);
			}	
			//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 = " Please add employee permission for this role";
					$err_column_tabview['error']["$excel_line_value$row"]  = $get_cell_value." - ".$msg_line; 
				}
			}
			if($field_type === 4){				
				if($date_type === 1 && $get_cell_value){					
					$excel_date = trim(Date::excelToDateTimeObject($sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));
					if(strpos($excel_date, '1900') !== false){
						$err_column_array['error']["$excel_line_value$row"] = $view_name;
						$msg_line = "Please enter valid date... Please map The Date Format Like (DD/MM/YYYY)";
						$err_column_tabview['error']["$excel_line_value$row"]  = $view_name." ".$msg_line;
					}								
				}
			}
		}
		$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){
				$employee_code    = $error_sts_arr[0]['employee_code'];
				$field_value      = $error_sts_arr[0]['field_value'];
				$field_name       = $error_sts_arr[0]['field_name'];
				$msg_line         = "Invalid - Duplicate $field_name [$field_value] found for Employee Code: $employee_code";
				$err_column_array['error']["$row"]   = $view_name;
				$err_column_tabview['error']["$row"] = $msg_line;
			}
		}
		if(((int)$stop_pay === 1) && $hold_reason === ''){
			$err_column_array['error']["$hold_line_val$row"] = $hold_view_name;
			$msg_line  		= ": Invalid - Empty Column is present - Please check the stop pay status..!";
			$err_column_tabview['error']["$hold_line_val$row"]  = $hold_view_name." ".$msg_line;
		}
		//FOR ACTIVITY NO
		if($activity_no && $wbs_element){
			$get_prime_id_qry       = ' SELECT '.$act_list_val_1.' FROM '.$act_table.' WHERE '.$act_list_val_2.' = "'.$activity_no.'" and act_wbs_id = "'.$wbs_element.'" ';
			$get_prime_id_info      = $this->db->query("CALL sp_a_run ('SELECT','$get_prime_id_qry')");
			$get_prime_id_rslt      = $get_prime_id_info->result();
			$get_prime_id_info->next_result();
			$activity_number        = $get_prime_id_rslt[0]->$act_list_val_1;
			if(!$activity_number){
				//echo "BSK $get_prime_id_qry <br/>";
				$err_column_array['error']["$excel_line_value$row"] = $view_name;
				$msg_line           = " Please check your Activity no..";
				$err_column_tabview['error']["$row"] = $msg_line; 
			}
		}
		if($wbs_element && $position && $activity_number && $category){
			//echo "BSK $wbs_element && $position && $activity_number && $category <br/>";
			if(!$emp_fil_rslt[$position][$wbs_element]){
				$err_column_array['error']["$excel_line_value$row"]    = $view_name;
				$msg_line = " Paystructure not Available for this WBS and Position...";
				$err_column_tabview['error']["$row"]  = $msg_line; 
			}elseif(!$emp_fil_rslt[$position][$wbs_element][$activity_number][$category]){
				//print_r($emp_fil_rslt[$position][$wbs_element]);
				//echo "BSK $row :: $wbs_element && $position && $activity_number && $category <br/>";
				$err_column_array['error']["$excel_line_value$row"]    = $view_name;
				$msg_line = " Paystructure not Available for this Activity No and Category...";
				$err_column_tabview['error']["$row"]  = $msg_line; 
			}
		}
		if($bank_account_num){
			$pattern = '/^[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)$/';
			if (preg_match($pattern, $bank_account_num)) {
				$err_column_array['error']["$excel_line_value$row"]    = $view_name;
				$msg_line = "Bank account number is invalid format please change excel format as text...!!";
				$err_column_tabview['error']["$row"]  = $msg_line; 
			}
		}
		//DOB AND DOJ 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){
			if((int)$str_dob > (int)$str_doj){
				$err_column_array['error']["$dob_line_val$row"] = $dob_view_name;
				$msg_line = " is not greater then date of joining";
				$err_column_tabview['error']["$dob_line_val$row"]  = $dob_view_name." ".$msg_line; 
			}else{ // Check Age validation based on UDS Conditions
				if($dob_date_value && $doj_date_value){ 
					$doj       = strtotime($doj_date_value); // or your date as well
					$dob       = strtotime($dob_date_value);
					$datediff  = $doj - $dob;
					$totdays   = round($datediff / (60 * 60 * 24));
					$years     = ($totdays+1)/365;	
					if($minimum_age > (int)$years){
						$err_column_array['error']["$dob_line_val$row"] = $dob_view_name;
						$msg_line = " minimum difference is $minimum_age years, please change the date?";
						$err_column_tabview['error']["$dob_line_val$row"]  = $dob_view_name." ". $msg_line; 
					}else
					if($maximum_age < (int)$years){
						$err_column_array['error']["$dob_line_val$row"] = $dob_view_name;
						$msg_line = " minimum difference is $maximum_age years, please change the date?";
						$err_column_tabview['error']["$dob_line_val$row"]  = $dob_view_name." ". $msg_line; 
					}					
				}
			}
		}
	}
	$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){
	//EMPLOYEE PERMISSION
	$emp_permission_qry   = 'SELECT * FROM cw_employee_permission WHERE cw_employee_permission.trans_status = 1 ';
	$emp_permission_data  = $this->db->query("CALL sp_a_run ('SELECT','$emp_permission_qry')");
	$emp_permission_rslt  = $emp_permission_data->result_array();
	$emp_permission_data->next_result();
	$emp_permission_arr   = array();
	foreach($emp_permission_rslt as $arr){
		$emp_permission_arr[$arr['role']][] = $arr;
	}
	//SAP ACTIVITY NUMBER GET CODE START BASED ON WBS
	$sap_act_no_qry       = 'SELECT prime_sap_activity_id AS prime_id,act_no,act_wbs_id FROM cw_sap_activity WHERE cw_sap_activity.trans_status = 1 GROUP BY cw_sap_activity.prime_sap_activity_id,cw_sap_activity.act_wbs_id';
	$sap_act_no_info      = $this->db->query("CALL sp_a_run ('SELECT','$sap_act_no_qry')");
	$sap_act_no_rslt      = $sap_act_no_info->result_array();
	$sap_act_no_info->next_result();
	foreach($sap_act_no_rslt as $arr){
	    $sap_act_no_arr[$arr['act_wbs_id']][$arr['act_no']] = $arr['prime_id'];
	}
	$bank_verify_qry      = 'SELECT cw_form_setting.label_name FROM cw_form_setting WHERE cw_form_setting.prime_module_id IN ("bank_details_verification") AND cw_form_setting.label_name NOT IN ("bank_app_status","employee_code","emp_name","role","bank_remarks","kyc_doc") AND cw_form_setting.trans_status = "1"';
	$bank_verify_data     = $this->db->query("CALL sp_a_run ('SELECT','$bank_verify_qry')");
	$bank_verify_rslt     = $bank_verify_data->result_array();
	$bank_verify_data->next_result();
	//BANK VERIFY INPUTS ARRAY 
	$bank_verify_arr      = array_column($bank_verify_rslt,"label_name","label_name");
	$excel_label_wise 	  = json_decode(json_encode($excel_format_result),true);
	$excel_label_wise     = array_reduce($excel_label_wise ?? [], function ($result, $arr) {
	    $result[$arr['label_name']] = $arr;
	    return $result;
	}, array());
	$excel_rslt = json_decode(json_encode($excel_format_result),true);
	$excel_rslt = array_reduce($excel_rslt ?? [], function($result, $arr){	
		$result[$arr['excel_line_column_name']] = $arr['excel_line_value'];
		return $result;
	}, array());
	$bank_details_arr   = array();
	$status_array	    = array();
	$formula_process    = array();
	$mid_log            = 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();
		$bank_details_arr = 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;
			$label_name 			= $excel_info->label_name;
			$dependent_pick_list	= (int)$excel_info->dependent_pick_list;
			$auto_prime_id	        = $excel_info->auto_prime_id;
			$auto_dispaly_value	    = $excel_info->auto_dispaly_value;
			$get_cell_value         = trim(iconv("UTF-8","ISO-8859-1",$sheet->getCell("$excel_line_value$row")->getCalculatedValue())," \t\n\r\0\x0B\xA0");
			if(in_array($excel_line_column_name,$bank_verify_arr)){
				if($excel_line_column_name === "date_of_birth" || $excel_line_column_name === "date_of_joining"){
					$get_cell_value = trim(Date::excelToDateTimeObject($sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));
					$bank_details_arr[$excel_line_column_name]=$get_cell_value;
				}else{
					$bank_details_arr[$excel_line_column_name]=$get_cell_value;
				}	
			}
			if($field_type === 4){
			// FOR DATE			
				if((int)$date_type === 1){
					if($sheet->getCell("$excel_line_value$row")->getCalculatedValue()){
						$get_cell_value = trim(Date::excelToDateTimeObject($sheet->getCell("$excel_line_value$row")->getValue())->format('Y-m-d'));
					}else{
						$get_cell_value ='';
					}
				}else{
					$get_cell_value         = trim(iconv("UTF-8","ISO-8859-1",$sheet->getCell("$excel_line_value$row")->getCalculatedValue())," \t\n\r\0\x0B\xA0");
				}				
			}else
			// FOR PICKLIST CHECK
			if(((int)$field_type === 5) || ((int)$field_type === 7) || ((int)$field_type === 9)){
				//DR CODE
				$get_pick_table = $excel_label_wise[$label_name]['pick_table'];
				$depand_join 	= "";
				$depand_where 	= "";
				if((int)$dependent_pick_list === 1){
					$depand_pick_input      = $excel_info->dependent_pick_input;
					$depand_field_type 		= (int)$excel_label_wise[$depand_pick_input]['field_type'];
					$depand_pick_table 		= $excel_label_wise[$depand_pick_input]['pick_table'];
					$depand_display_val 	= $excel_label_wise[$depand_pick_input]['pick_display_value'];
					$depand_list_import 	= (int)$excel_label_wise[$depand_pick_input]['pick_list_import'];
					$depand_pick_list 		= $excel_label_wise[$depand_pick_input]['pick_list'];
					//dr start new
					$depand_auto_prime_id   = $excel_label_wise[$depand_pick_input]['auto_prime_id'];
					$depand_auto_dispaly    = $excel_label_wise[$depand_pick_input]['auto_dispaly_value'];
					//dr end new
					$depand_tbl1 			= $excel_label_wise[$label_name]['table_column1'];
					$depand_tbl2 			= $excel_label_wise[$label_name]['table_column2'];
					$depand_excel_val       = $excel_rslt[$depand_pick_input];
					
					$depand_cell_value      = ucwords(trim($sheet->getCell("$depand_excel_val$row")->getValue()));
					//dr start new
					if($depand_field_type === 5){
						$depand_pick_list_val   = explode(",",$depand_pick_list ?? "");
						$depan_pick_list_val_1  = $depand_pick_list_val[0];
						$depan_pick_list_val_2  = $depand_pick_list_val[1];

						if((int)$depand_list_import === 1){
							$depand_where_col 	 =  $depan_pick_list_val_1;
						}else
						if((int)$depand_list_import === 2){
							$depand_where_col 	 =  $depan_pick_list_val_2;
						}
					}else
					if($depand_field_type === 9){
						$depand_where_col 	     =  $depand_auto_dispaly;
					}
					$get_display_val   = $excel_label_wise[$label_name]['pick_display_value'];
					$get_list_import   = $excel_label_wise[$label_name]['pick_list_import'];
					$get_pick_dispaly  = $excel_label_wise[$label_name]['pick_display_value'];
					//dr start new
					$get_auto_prime_id = $excel_label_wise[$label_name]['auto_prime_id'];
					$get_auto_dispaly  = $excel_label_wise[$label_name]['auto_dispaly_value'];
					if($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];

						if((int)$get_list_import === 1){
							$where_col 	 =  $pick_list_val_1;
						}else
						if((int)$get_list_import === 2){
							$where_col 	 =  $pick_list_val_2;
						}
						// $get_pick_dispaly = $pick_list_val_1;
					}else
					if($field_type === 9){
						$where_col 	        =  $get_auto_dispaly;
						$pick_list_val_1    = $auto_prime_id;
						if($label_name === "wbs_element"){
							$sap_wbs_query  = 'select prime_sap_wbs_id,wbs_id,wbs_project_id,wbs_network_id from cw_sap_wbs where wbs_id = "'.$get_cell_value.'"';
							$sap_wbs_data   = $this->db->query("CALL sp_a_run ('SELECT','$sap_wbs_query')");
							$sap_wbs_result = $sap_wbs_data->result_array();
							$sap_wbs_data->next_result();	

							$wbs_project    = $sap_wbs_result[0]['wbs_project_id'];	
							$wbs_network    = $sap_wbs_result[0]['wbs_network_id'];	
						}
					}
				}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.'"';	
							}
							$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;
									$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 === 1){
								if($pick_table !== $this->prime_table){
									$pick_id     = $pick_result[0]->$pick_list_val_1;
									$get_cell_value = $pick_id;
								}
							}
						}
					}else// FOR AUTOCOMPLETE CHECK
					if($field_type === 9){
						$pick_query  = 'select '.$auto_prime_id.' from '.$pick_table.' where '.$auto_dispaly_value.' = "'.$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){
								$get_cell_value = $pick_result[0]->$auto_prime_id;
							}
						}
						// //DR CODE FOR ACTIVITY NO AND NETWORK ID
						if($label_name === "wbs_element"){
							$sap_wbs_query  = 'select prime_sap_wbs_id,wbs_id,wbs_project_id,wbs_network_id from cw_sap_wbs where wbs_id = "'.$get_cell_value.'"';
							$sap_wbs_data   = $this->db->query("CALL sp_a_run ('SELECT','$sap_wbs_query')");
							$sap_wbs_result = $sap_wbs_data->result_array();
							$sap_wbs_data->next_result();	
							$wbs_project    = $sap_wbs_result[0]['wbs_project_id'];	
							$wbs_network    = $sap_wbs_result[0]['wbs_network_id'];	
						}
						$emp_location       =    '';
						if($label_name === "personal_code"){
							$per_area_query = 'select prime_sap_personal_area_id,personal_code,personal_name from cw_sap_personal_area where cw_sap_personal_area.personal_code = "'.$get_cell_value.'" and cw_sap_personal_area.trans_status = 1';
							$per_area_data  = $this->db->query("CALL sp_a_run ('SELECT','$per_area_query')");
							$per_area_rslt  = $per_area_data->result();
							$per_area_data->next_result();
							$emp_location   = $per_area_rslt[0]->personal_name;
						}
					}
				}
			}
			if($field_isdefault === 1){
				$get_cell_value    = str_replace("'",'^', $get_cell_value);
				if($excel_line_column_name !== 'project_id' && $excel_line_column_name !== 'network_id' && $excel_line_column_name !== 'emp_location' && $excel_line_column_name !== 'activity_no' ){
					$prime_column_val .= $excel_line_column_name . ",";
					$prime_cell_val   .= "\'" . $get_cell_value . "\',";
					$mid_log[$excel_line_column_name] = $get_cell_value;
				}
				$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 ';
					}
					if($excel_line_column_name !== 'project_id' && $excel_line_column_name !== 'network_id' && $excel_line_column_name !== 'emp_location' && $excel_line_column_name !== 'activity_no' ){
						$update_cell_val   = '"'.$get_cell_value.'",';
						$prime_upd_query  .= $excel_line_column_name."=".$update_cell_val;
						$mid_log[$excel_line_column_name] = $get_cell_value;
					}
					$emp_log[$excel_line_column_name] = $get_cell_value;
				}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($excel_line_column_name !== 'project_id' && $excel_line_column_name !== 'network_id' && $excel_line_column_name !== 'emp_location' && $excel_line_column_name !== 'activity_no'){
						$update_column_val = $excel_line_column_name;
						$update_cell_val   = '"'.$get_cell_value.'",';
						$prime_upd_query  .= $update_column_val."=".$update_cell_val;
					}
				}
				//old application insert query building details start --18JAN2020
				if($excel_line_column_name === "employee_code"){
					$password  = md5($get_cell_value);
					$user_name = $get_cell_value;
					$code      = $get_cell_value;
					$emp_code_arr[$row]  = $get_cell_value;
				}
				if($excel_line_column_name === "date_of_joining"){					
					$doj      = $get_cell_value;
				}
				if($excel_line_column_name === "emp_name"){
					$empname  = $get_cell_value;
				}
				if($excel_line_column_name === "department"){
					$department    = $get_cell_value;
					$depart_query  = 'select department from cw_department where prime_department_id = "'.$department.'" and trans_status =1';
					$depart_data   = $this->db->query("CALL sp_a_run ('SELECT','$depart_query')");
					$depart_result = $depart_data->result();
					$depart_data->next_result();
					$department    = $depart_result[0]->department;
				}
				if($excel_line_column_name === "designation"){
					$designation   = $get_cell_value;
					$design_query  = 'select designation from cw_designation where prime_designation_id = "'.$designation.'"  and trans_status =1';
					$design_data   = $this->db->query("CALL sp_a_run ('SELECT','$design_query')");
					$design_result = $design_data->result();
					$design_data->next_result();
					$designation   = $design_result[0]->designation;
				}
				if($excel_line_column_name === "gender"){
					$gender = $get_cell_value;
					if((int)$gender === 2){
						$gender = "F";
					}else{
						$gender = "M";
					}
				}
				if($excel_line_column_name === "date_of_birth"){
					$dob   = $get_cell_value;
					$today = new datetime(date("Y-m-d"));
					$age   = 0; 
					if($dob){
						$dob    = new datetime($get_cell_value);
						$differ = $today->diff($dob);
						$age    = (string)$differ ->y;
					}
				}
				if($excel_line_column_name === "marital_status"){
					$marital_status    = $get_cell_value;
					if((int)$marital_status === 1){
						$marital_status = "Married";
					}else{
						$marital_status = "UnMarried";
					}
				}
				if($excel_line_column_name === "role"){
					$role              = $get_cell_value;
				}
				if($excel_line_column_name === "user_right"){
					$user_right        = (int)$get_cell_value;
				}
				if($excel_line_column_name === "wbs_element"){
					$wbs_id            = $get_cell_value;
				}
				if($excel_line_column_name === "personal_code"){
					$personal_area_id  = $get_cell_value;
				}
				if($excel_line_column_name === "position"){
					$position_id       = $get_cell_value;
				}
				if($excel_line_column_name === "activity_no"){
					$act_no            = $get_cell_value;
				}
				if($act_no && $wbs_id){
					$activity_id       = $sap_act_no_arr[$wbs_id][$act_no];
				}
				//old application insert query building details end --20JAN2020
			}
			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.'",';
				}
			}
		}
		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;
					//for grants insert function 
					$emp_perm_grants_ary     = [];
					if(isset($emp_permission_arr[$user_right])){   #NB[22-03-2024]
					    $emp_perm_grants_ary = [$user_right => $emp_permission_arr[$user_right]];
					}
					if((int)$import_type === 1){
						if((int)$exist_count === 0){
							if($wbs_project){
								$prime_column_val .= 'project_id,';
								$prime_cell_val   .= '"'.$wbs_project.'",';
							}
							if($wbs_network){
								$prime_column_val .= 'network_id,';
								$prime_cell_val   .= '"'.$wbs_network.'",';
							}
							if($emp_location){
								$prime_column_val .= 'emp_location,';
								$prime_cell_val   .= '"'.$emp_location.'",';
							}
							if($activity_id){
								$prime_column_val .= 'activity_no,';
								$prime_cell_val   .= '"'.$activity_id.'",';
							}
							$prime_column_val .= "emp_age,hr_status,user_name,password,entry_flag,sap_status,trans_created_by,trans_created_date";
							$prime_cell_val   .= '"'.$age.'","3","'.$user_name.'","'.$password.'","e","5","'.$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;
							$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);
								$imp_sts = False;
							}	
						}else{
							$imp_sts = True;
						}
					}else{
						if((int)$exist_count === 1){
							$old_bank_details_qry  = 'select bank_account_number,bank_key,ifsc_code,personal_code,project_id,date_of_birth,date_of_joining,aadhar_card_no,wbs_element,position,activity_no from cw_employees where employee_code ="'.$code.'"';
							$old_bank_info         =  $this->db->query("CALL sp_a_run ('SELECT','$old_bank_details_qry')");
							$old_bank_rslt         = $old_bank_info->result();
							$old_bank_info->next_result();
							if($wbs_project){
								$prime_upd_query .= 'project_id = "'.$wbs_project.'",';
							}
							if($wbs_network){
								$prime_upd_query .= 'network_id = "'.$wbs_network.'",';
							}
							if($emp_location){
								$prime_upd_query .= 'emp_location = "'.$emp_location.'",';
							}
							$code_info   = $this->db->query("CALL sp_a_run ('SELECT','SELECT prime_employees_id,employee_code,emp_name,role FROM `cw_employees` where employee_code = ".$code." and trans_status = 1')");
							$code_result = $code_info->result();
							$code_info->next_result();
							$employee_code       = $code_result[0]->employee_code;
							$prime_emp_id        = $code_result[0]->prime_employees_id;
							$emp_name            = $code_result[0]->emp_name;
							$emp_log['emp_name'] = $emp_name;
							$mid_log['emp_name'] = $emp_name;
							//UPDATE MIDDLEWARE AND EMP LOG,BANK DETAIL TBL.
							if($mid_log){
								$this->employee_log($prime_emp_id,$emp_log);	
								$this->middleware_update($prime_emp_id,$mid_log,$employee_code); 
							}
							if($bank_details_arr){
								$this->bank_details_verification_upd($old_bank_rslt,$bank_details_arr,$code_result);
							}	
							$upd_prime_id        = (int)$exist_result[0]->$prime_id;
							$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){
								//employee permission grants insert function
								if(!empty($emp_perm_grants_ary)){
									$update_grants_sts = $this->update_grants($upd_prime_id,$emp_perm_grants_ary);
								}
								$status_info['Status'] = "Updated to DB";
							}else{
								$status_info['Status'] = "Not Updated.. Try After Sometime..";
							}									
						}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;
		}
	}
	//FOR UPDATE EMPLOYEE MASTER AFTER IMPORT(AMENDMENT)
	// $emp_codes       = '"'.implode('","',$emp_code_arr).'"';
	// if((int)$import_type === 2){
	// 	$emp_tbl_upd_qry  ='UPDATE cw_employees ce JOIN cw_pay_structure ps ON ps.personal_code =ce.personal_code AND ps.wbs_element=ce.wbs_element AND ps.position=ce.position AND ps.status=1	SET ce.activity_no=ps.activity_no ,ce.professional_tax_location=ps.tax_location,ce.role=ps.category WHERE ce.employee_code IN ('.$emp_codes.')';
	// 	$this->db->query("CALL sp_a_run ('UPDATE','$emp_tbl_upd_qry')");
	// }
	
	if($imp_sts){
		$table_info = "";
		$status     = False;
		$msg        = "Invalid Excel Format to Import";
	}else{
		$status     = true;
		$msg        = "Successfully files imported in database!!!";
		$table_info = $this->get_excel_import_ui($status_array);
	}
	/*$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_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));
}

public function bank_details_verification_upd($old_bank_rslt,$bank_details_arr,$emp_code_result){
	$created_on = date("Y-m-d H:i:s");
	$employee_code = $emp_code_result[0]->employee_code;
	$role          = $emp_code_result[0]->role;
	$emp_name      = $emp_code_result[0]->emp_name;
	$old_key = "";
	$old_value = "";
	$new_key = "";
	$new_value = "";
	foreach($old_bank_rslt[0] as $key => $value){
		if($key === "bank_account_number" || $key === "ifsc_code" || $key === "bank_key"){
			$old_key   .= 'old_'.$key.","; 
			$old_value .= '"' . $value . '",';
		}else{			
			if (!array_key_exists($key, $bank_details_arr)) {
				$old_key   .= $key.","; 
				$old_value .= '"' . $value . '",';
			}			
		}		
	}
	foreach($bank_details_arr as $label_name => $val){
		if($label_name === "bank_key" && $val === "9200"){
			$new_key    .= $label_name.","; 
			$new_value  .= '"'. $val .'",';
		}else
		if($label_name === "date_of_birth" || $label_name === "date_of_joining"){
			$date        = date('Y-m-d',strtotime($val));
			$new_key    .= $label_name.","; 
			$new_value  .= '"'.$date.'",';
		}else{
			$new_key    .= $label_name.","; 
			$new_value  .= '"'. $val .'",';
		}
	}
	$bank_pen_del_qry   = 'UPDATE cw_bank_details_verification SET trans_status = "0",trans_updated_by = "'.$this->logged_id.'",trans_updated_date = "'.$created_on.'" WHERE cw_bank_details_verification.employee_code = "'.$employee_code.'" and cw_bank_details_verification.bank_app_status = 1 and cw_bank_details_verification.trans_status = 1';
	$bank_pen_del_info  = $this->db->query("CALL sp_a_run ('UPDATE','$bank_pen_del_qry')");

	$bank_details_ins_qry = 'insert into cw_bank_details_verification(employee_code,emp_name,role,'.$old_key.''. $new_key.'trans_created_by,trans_created_date)values("'.$employee_code.'","'.$emp_name.'","'.$role.'",'.$old_value.''.$new_value.'"'. $this->logged_id .'","'.$created_on.'")';
	$bank_detail_info   = $this->db->query("CALL sp_a_run ('INSERT','$bank_details_ins_qry')");
	$bank_detail_rslt   = $bank_detail_info->result();
	$bank_detail_info->next_result();
}


//EMPLOYEES TABLE LOG FOR EVERY UPDATE 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;
	$emp_label_name    = array_keys($emp_log);
	$emp_label_value   = implode(",",$emp_label_name ?? []);
	$emp_data_qry      = 'select '.$emp_label_value.' from cw_employees where prime_employees_id = "'.$emp_id.'" and trans_status = 1';
	$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'];
	$emp_data_dif   = array_diff_assoc($fin_emp_result,$emp_log);
	$prime_qry_value  = "";
	$prime_qry_key    = "prime_employees_id,employee_code,emp_name,label_name,old_value,new_value,trans_created_by,trans_created_date";
	foreach($emp_data_dif as $emp_key=>$emp_value){		
		$old_label_val  = $fin_emp_result[$emp_key];
		$new_label_val  = $emp_log[$emp_key];
		if(($old_label_val != $new_label_val) && ($old_label_val !=='0.00' && $new_label_val !=='') && ($old_label_val !=='0000-00-00' && $new_label_val !=='')){
			$prime_qry_value .= "(\"$emp_id\",\"$emp_code\",\"$emp_name\",\"$emp_key\",\"$old_label_val\",\"$new_label_val\",\"$logged_id\",\"$created_on\"),";
		}
	}
	if(!empty($prime_qry_value)){
		$prime_qry_value = rtrim($prime_qry_value,',');
		$prime_insert_query = "insert into cw_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();
		$insert_id           = (int)$insert_result[0]->ins_id;
	}
}

//UPDATE MIDDLEWARE TABLE AMENDMENT IMPORT 
public function middleware_update($prime_emp_id,$emp_log,$emp_code){
	$emp_label_name  = array_keys($emp_log);
	$emp_label_value = implode(",",$emp_label_name ?? []);
	$post_array      = array('emp_name','date_of_birth','stop_pay_code','father_name','aadhar_card_no','pan_number','emp_uan','mobile_number','emp_esi_location','emp_esi_no','emp_pf_no','husband_name','resignation_date');
	$from_query      = 'SELECT '.implode(",",$post_array ?? []).' FROM cw_employees WHERE cw_employees.trans_status = 1 AND prime_employees_id = "'. $prime_emp_id .'" ';
	$form_data       = $this->db->query("CALL sp_a_run ('SELECT','$from_query')");
	$form_result     = $form_data->result_array();
	$form_data->next_result();
	$prev_data       = $form_result[0];
	foreach($prev_data as $key => $val){
		if($key === 'resignation_date'){
			if($val === '0000-00-00' || $val === NULL){
				$previous_data[$key] = "";						
			}
		}else{
			$previous_data[$key] = $val;
		}
	}
	if($previous_data){
		$result       = array_intersect_key($emp_log,$previous_data);				
		$arraycompare = array_diff_assoc($result,$previous_data);	
	} 
	if($arraycompare['bank_key'] === '9200'){
		$arraycompare['bank_account_number'] = '';
		$arraycompare['ifsc_code']           = '';
	}	
	if($arraycompare){
		$sap_post_qry = 'INSERT INTO uds_middleware.cw_employees_update(employee_code,'.implode(",",array_keys($arraycompare ?? []) ?? []).') VALUES("'.$emp_code.'","'.implode('","',array_values($arraycompare ?? []) ?? []).'")';
		$mid_info     = $this->db->query("CALL sp_a_run ('RUN','$sap_post_qry')");
		if($mid_info){
			$emp_upd_qry = 'UPDATE cw_employees SET sap_upd_status = "1" WHERE prime_employees_id = "'. $prime_emp_id .'"';
			$this->db->query("CALL sp_a_run ('RUN','$emp_upd_qry')");
		}
	}
}

public function pay_struct_exist_fun($personal_area_id,$wbs_id,$position_id){
	//FRIST WE CHECK MI FMS TABLE
	$mi_ext_check_qry    = 'select cw_pay_structure.prime_pay_structure_id AS prime_id FROM cw_pay_structure WHERE cw_pay_structure.personal_code="'.$personal_area_id.'" AND cw_pay_structure.wbs_element="'.$wbs_id.'" AND cw_pay_structure.position="'.$position_id.'" AND cw_pay_structure.trans_status=1 AND cw_pay_structure.status=1';
	$pay_ext_check_info  = $this->db->query("CALL sp_a_run ('SELECT','$mi_ext_check_qry')");
	$pay_ext_check_rslt  = $pay_ext_check_info->result();
	$pay_ext_check_info->next_result();
	return $pay_ext_check_rslt;
}

public function update_grants($ins_id,$emp_perm_grants_arr){
	//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.'"';
		$success_data    = $this->db->query("CALL sp_a_run ('RUN','$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)";
		$insert_grants_info  = $this->db->query("CALL sp_a_run ('INSERT','$insert_grants_qry')");
		$insert_grants_rslt  = $insert_grants_info->result();
		$insert_grants_info->next_result();
		$insert_id           = (int)$insert_grants_rslt[0]->ins_id;
		if($insert_id){
			return true;
		}else{
			return false;
		}
	}
}
/* USED IN BOTH EMPLOYEE AND CUSTOMER MODULE - END*/


//FUNCTION FOR INSERT A GRANTS PERMISSION IN USER BASED
public function grants_permission_ins_fun($employee_code,$prime_id,$user_right){
	$ins_per_grants_qry    = 'INSERT INTO cw_grants(permission_id,prime_employees_id,grants_menu_id,grants_sub_menu_id,access_add,access_update,access_delete,access_search,access_export,access_import) SELECT permission_id,cw_employees.prime_employees_id,grants_menu_id,grants_sub_menu_id,access_add,access_update,access_delete,access_search,access_export,access_import FROM cw_employee_permission inner join cw_employees on cw_employees.user_right = cw_employee_permission.role WHERE cw_employee_permission.trans_status = 1 and cw_employee_permission.role = "'.$user_right.'" and cw_employees.prime_employees_id in('.$prime_id.')';
	$ins_per_grants_info   = $this->db->query("CALL sp_a_run ('INSERT','$ins_per_grants_qry')");
	$ins_per_grants_rslt   = $ins_per_grants_info->result();
	$ins_per_grants_info->next_result();
	$insert_id             = '"'.$ins_per_grants_rslt[0]->ins_id.'"';	
}

//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 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(\$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 ===================*/
	/* ==============================================================*/
	
	/*public function curl($emp_data){
		$postdata = '';
		foreach($emp_data as $key => $val){ 
			$postdata .= $key . '='.$val.'&'; 
		}
		$postdata = rtrim($postdata, '&');
		$url_path = base_url();
		$url = $url_path."app/timeoffice_api.php?frm=save_emp";
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_POST, count($postdata));
		curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$result= curl_exec($ch);
		curl_close($ch);
	}*/
/* ==============================================================*/
/* ================== PRINT OPERATION - START ===================*/
/* ==============================================================*/

	//NEHA EDIT START
	public function sent_print($view_id){
		
		if($this->control_name === "offer_letter"){
			$cat_query = 'select category 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;
			$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;
		$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 print_design_for = "'.$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);
										$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);
		$data['print_design'] = $print_design;
		return $data;
	}
	//NEHA EDIT END
	
	//number to words changed in payslip
	public function numbertowords($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 $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(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$sheet_name        = array();
		$spreadsheet       = new Spreadsheet();
		$sheet_count       = $spreadsheet->getSheetCount();
		for($i= 0; $i< $sheet_count; $i++){
			$sheet         = $spreadsheet->getSheet($i);
			$sheet_name[]  = $sheet->getTitle();
		}
		echo json_encode(array('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.'"';
		//and cw_loan_installment.install_month ='.$loan_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['module_id']     = $this->control_name;
		$data['encKey']        = $this->generateKey();	
		$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(){
		$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_status=0,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,view_name,excel_line_column_name,excel_line_value from cw_util_excel_format_line inner join cw_form_setting on cw_form_setting.label_name = excel_line_column_name 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_form_setting.prime_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 cw_form_setting.label_name';
		$excel_format   = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
		$excel_result   = $excel_format->result();
		$excel_format->next_result();	
		$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){
			$excel_line_column_name = $excel->view_name;
			$excel_line_value       = $excel->excel_line_value;
			$worksheet->getCell($excel_line_value.'1')->setValue($excel_line_column_name);
		}
		$filename= $module_id."_".$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(){
		/* 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;

		$employee_code          = $this->input->post('emp_code');
		$date_of_joining_query  = "";
		if($component){
			$date_of_joining_query  = 'SELECT role as category,date_of_joining,department,first_level_approval,second_level_approval,approve_type,'.$component.' from cw_employees WHERE employee_code = "'. $employee_code .'" and  trans_status = 1';
		}else{
			$date_of_joining_query  = 'SELECT role as category,date_of_joining,first_level_approval,second_level_approval,approve_type from cw_employees WHERE employee_code = "'. $employee_code .'" and  trans_status = 1';
		}
		$date_of_joining_info   = $this->db->query("CALL sp_a_run ('SELECT','$date_of_joining_query')");
		$date_of_joining_rlst   = $date_of_joining_info->result();
		$date_of_joining_info->next_result();
		$date_of_joining        = date("d-m-Y",strtotime($date_of_joining_rlst[0]->date_of_joining));
		$first_level_approval   = $date_of_joining_rlst[0]->first_level_approval;
		$second_level_approval  = $date_of_joining_rlst[0]->second_level_approval;
		$component_value    	= $date_of_joining_rlst[0]->$component;
		$approve_type    	    = $date_of_joining_rlst[0]->approve_type;
		$category        	    = $date_of_joining_rlst[0]->category;
		$department        	    = $date_of_joining_rlst[0]->department;

		//ARRAY FOR PICKLIST WISE EMPLOYEE DETAILS FROM EMPLOYEE TABLE
		// $this->emp_pick_arr     = $date_of_joining_info->result_array();
		//GTE DEFAULT FINANCIAL YEAR
		$financial_info         = $this->leave_financial_info;
		$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 FORM DATE AND TO DATE VALIDATION
		$salary_start_date     = "";
		$salary_end_date       = "";
		if($date_of_joining_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,$starting_date,$ending_date);
			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'];

				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, '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..."));
		}		
	}
	//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,$starting_date,$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 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));
	        	//for salary start month
				// if($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;
					// if($process_month !== date("m-Y",strtotime($starting_date))){
					// 	// $end_date         = "$day_end-".date('m-Y',$process_month);
					// 	$next_month_date  = date('d-m-Y',strtotime("+1 month",strtotime("$day_end-".$process_month)));
					// 	$day_end          = date('d',strtotime($next_month_date));
					// }else{
					// 	//for salary start month
					// 	$day_start      = date('d',strtotime($starting_date));
					// 	$day_end        = date('d',strtotime($ending_date));
					// }
					
				}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 === ""){
				// echo json_encode(array('success' => FALSE, 'message' => "Please Set Month Day Options for this Category..."));
				// exit(0);
				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."-".$process_month));
					$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);
				return $month_day_arr;
			}
		}else{
			// echo json_encode(array('success' => FALSE, 'message' => "Please Set Month Day for this Category..."));
			// exit(0);
			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         = "";
			$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
				$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           = 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;
		}
	}
	public function last_payroll_status($starting_date,$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.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));
			//for salary start month
			// if($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));
			}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));
			}
			// $month_day_arr      = "salary_end_date" => $salary_end_date;
			return $salary_end_date;
		}

	}
	//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){
		$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));
		// Load pdf library
        $this->load->library('pdf');
			// Load HTML content 
		$this->dompdf->loadHtml($table_data);
			// (Optional) Setup the paper size and orientation
		$this->dompdf->setPaper('A4', 'portrait');
			// Render the HTML as PDF
		$this->dompdf->render();
			// Output the generated PDF (1 = download and 0 = preview)
		$output = $this->dompdf->output();
		
		//$folder = "./".$controller_name."/".$controller_name."_".$category_name;
		$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;
		}
	}
	/* Dynamic mail Start - Latha*/
	public function dynamic_mail_sent($form_id,$pick_array,$previous_data){
		$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.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 = "";
			//Email Info
			$email_info_qry    	= 'select cw_email_info.email_info_name,cw_email_info.email_attach_column,cw_email_info.prime_email_info_id,email_design,email_subject 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.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();
			$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_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 order by cw_email_block.email_block_type';
			$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());

			$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());

			$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 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;
				$email_subject   		= $value->email_subject;
				$email_design   		= $value->email_design;
				$email_attach_column	= $value->email_attach_column;
				$pdf_name 				= $value->email_info_name;
				$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'];	
					$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;
									$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[$prime_email_block_id]['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,',');
				}					
			}
		}
		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);
						$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);
					}
				}
			}
		}
		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 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;
		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 = true; // This Must Be True
				$mail->Username = $username; // Your Email Address
				$mail->Password = $password; // Your Password
				$mail->SMTPSecure = 'SSL'; // Check Your Server's Connections for TLS or  SSL
				$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){
						$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){
						$mail->AddCC($bccs_mails);
					}
				}
				if(file_exists($attachment)){
					$mail->addAttachment($attachment);	
				}
				$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();
		$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, true);
		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;
		// 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 = "'.$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) {
										}
									});
								}
							</script>";
							// <a href='#' class='btn btn-primary btn-sm' id= 'approve' onclick = 'approve()'>Approve</button>
							$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){
								// echo "DR::$replace_val::$value";
								$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
										// echo "DR::$key";
										$start         = "@".$key."_";
										$end           = "_".$key."@";
										$replace_val   = $start.$column.$end;
										$replace_val   = $start.$column.$end;
										$date_value    = date_create($value);
										$replace_value = date_format($date_value,$formate);
										$print_design  = str_replace($replace_val,$replace_value,$print_design);
									}
								}
							}else
							if($print_block_type === 2){
								$td_line .= "<td style='text-align:center;'>$value</td>";
							}
							if($count === 1){
								$head_name = ucwords(str_replace("_"," ",$column));
								$th_line .= "<th style='text-align:center;'>$head_name</th>";
							}
						}
					}
					if($print_block_type === 2){
						if($count === 1){
							$th_line  = "$th_line";
						}
						$tr_line .= "<tr>$td_line</tr>";
					}
				}
				if($print_block_type === 2){
					$table_list  = "<table style='width:100%;'><thead>$th_line</thead><tbody>$tr_line</tbody></table>";
					$replce_block = "@".strtolower(str_replace(" ","_",$print_block_name))."@";
					$print_design = str_replace($replce_block,$table_list,$print_design);
				}
			}
			$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){
		// echo "$to_email::$first_to_email::$second_to_email::$body_content::";
		// die;
		// if($to_email){
		// 	$config_query  = 'SELECT smtp_server,sender_name,bcc,port_no,sender_email,mail_username,mail_password 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;
		// 	try{
		// 		$mail = new PHPMailer();
		// 		//$mail->SMTPDebug = 3; 
		// 		$mail->IsSMTP();
		// 		$mail->Host = $smtp_server; // Your SMTP Parameter
		// 		//$mail->Host = 'localhost';
		// 		// $mail->SMTPDebug = 2;
		// 		$mail->Port     = $port_no; // Your Outgoing Port
		// 		$mail->SMTPAuth = true; // This Must Be True
		// 		$mail->Username = $username; // Your Email Address
		// 		$mail->Password = $password; // Your Password
		// 		$mail->SMTPSecure = 'SSL'; // Check Your Server's Connections for TLS or SSL
		// 		$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->addAttachment($folder); // Add attachments
		// 				$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){
		// echo "folder => $folder,file_name => $file_name,set_paper => $set_paper,paper_size => $paper_size,pdf_set_password => $pdf_set_password";
		// 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((int)$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;
		//echo "BSK $folder,$file_name,$set_paper,$paper_size,$pdf_set_password"; die;
		$oldmask 	= umask(0);
		if (!file_exists($folder)){
			mkdir($folder, 0777, true);
		}
		//File write
		file_put_contents($folder."/".$file_name.".pdf" , $final_html);
		chmod($folder."/".$file_name.".pdf", 0777);
		umask($oldmask);
		$path = $folder."/".$file_name.".pdf";	
		return $path;
	}

	public function generate_pdf_access($table_data,$folder,$file_name,$set_paper,$paper_size,$pdf_set_password){
		//echo $table_data; die;		
		// Load pdf library
        $this->load->library('pdf');
		// Load HTML content 
		$this->dompdf->loadHtml();
		// (Optional) Setup the paper size and orientation
		$this->dompdf->setPaper($paper_size, $set_paper);
		// Render the HTML as PDF
		$this->dompdf->render($table_data);
		define('DOMPDF_ENABLE_AUTOLOAD', false);
		if($pdf_set_password === "1"){
			//SET Production
			$dob = date("d-m-Y",strtotime($this->emp_data_result[$file_name]['date_of_birth']));
			$doj = date("d-m-Y",strtotime($this->emp_data_result[$file_name]['date_of_joining']));
			$password = $dob."@".$doj;
			$password = str_replace("-", "", $password);
			$this->dompdf->get_canvas()->get_cpdf()->setEncryption($password, $password);
		}        
		// Output the generated PDF (1 = download and 0 = preview)
		$output 	= $this->dompdf->output();
		$final_html = $output;
		//echo "BSK $folder,$file_name,$set_paper,$paper_size,$pdf_set_password"; die;
		$oldmask 	= umask(0);
		if (!file_exists($folder)){
			mkdir($folder, 0777, true);
		}

		//File write
		file_put_contents($folder."/".$file_name.".pdf" , $final_html);
		chmod($folder."/".$file_name.".pdf", 0777);
		umask($oldmask);
		$path = $folder."/".$file_name.".pdf";
		
		return $path;
	}
	// Experience 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 = 'select * from cw_company_information where cw_company_information.trans_status = 1';
		$comp_info    = $this->db->query("CALL sp_a_run ('SELECT','$company')");
		$comp_result  = $comp_info->result();
		$comp_info->next_result();
		$this->comp_info = $comp_result;
		return $comp_result;
	}
	//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;
		}
	}
	//This Conditions Check for permission and manual punch and business trip
	public function check_exist_shift_sts($component_value,$employee_code,$shift_date){
		$financial_year_id  = $this->leave_financial_info[0]->prime_leave_financial_year_id;	

		$shift_request_qry  = 'SELECT count(*) 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,2) 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();
		$shift_request_info->next_result();	
		$shift_count        = (int)$shift_request_rslt[0]->count;

		if($shift_count){
			return false;
		}else{
			return true;
		}
	}
	//this condition check for shift change request
	public function check_exist_request_sts($component_value,$employee_code,$shift_date){
		$financial_year_id     = $this->leave_financial_info[0]->prime_leave_financial_year_id;	

		$permission_entry_qry  = 'SELECT count(*) 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;

		$man_punch_check_qry   = 'SELECT COUNT(*) as count from cw_manual_punch_entry where cw_manual_punch_entry.employee_code = "'.$employee_code.'" and cw_manual_punch_entry.in_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;
		if($permission_count || $mp_check_count){
			return false;
		}else{
			return true;
		}
	}
	//permission validation exist check
	public function permission_setting_check($component_value,$employee_code,$permission_date,$shift_name,$in_time,$out_time,$total_time){
		$permission_setting_qry     = 'SELECT allowed_per_month,allowed_per_day,no_of_permissions FROM cw_permission_setting WHERE FIND_IN_SET("'.$component_value.'", cw_permission_setting.component_value) 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;

		$salary_start_date   = "";
		$salary_end_date     = "";
		if($allow_per_month && $no_of_permissions && $allow_per_day){
			if($allow_per_month <= $total_time){
				echo json_encode(array('success' => FALSE, 'message' => "You Have Reached Maximum Hours per Month?"));
				exit(0);
			}else
			if($allow_per_day <= $total_time){
				echo json_encode(array('success' => FALSE, 'message' => "You Have Reached Maximum Hours per Day?"));
				exit(0);
			}else{
				//GTE DEFAULT FINANCIAL YEAR
				$financial_info        = $this->leave_financial_info;
				$prime_financial_id    = $financial_info[0]->prime_leave_financial_year_id;	
				$starting_date         = date('Y-m-d',strtotime($financial_info[0]->starting_date));	
				$ending_date           = date('Y-m-d',strtotime($financial_info[0]->ending_date));	
				//check month day for this category
				$month_day_info        = $this->month_day_info($component_value,$starting_date,$ending_date);
				if(count($month_day_info ?? [])){
					$salary_start_date     = date("Y-m-d",strtotime($month_day_info["salary_start_date"]));
					$salary_end_date       = date("Y-m-d",strtotime($month_day_info["salary_end_date"]));

					$check_sts             = false;
					if($permission_date >= $salary_start_date && $permission_date <= $salary_end_date){
						$check_sts         = true;
					}

					if($check_sts){
						$permission_entry_qry     = 'SELECT count(*) 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 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){
							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){
								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(*) 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';
								$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();

								$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..Please Check it?"));
									exit(0);
								}else
								if($day_permission_time >= $allow_per_day){
									echo json_encode(array('success' => FALSE, 'message' => "Already You Have Reached Maximum Hours per Day?"));
									exit(0);
								}else{
									return true;
								}
							}

						}
					}else{
						echo json_encode(array('success' => FALSE, "message" => "Don't Add Your Permission Request Because Payroll should be 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 Add a Setting for Permission..?"));
			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){
			// if($in_time < $out_time || $text === "day_type"){
				$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{
		// if($in_date !== $out_date){
		// 	if($in_time > $out_time){
				$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");
			// }else{
			// 	$total_time  = "";
			// }
		}
			
		if($total_time && ($days === 0 || $days === 1)){
			return $total_time;
		}else{
			return false;
		}
	}

	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());
		// $category_name  = $category_rslt[0]['category_name'];
		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"){
				$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{
				$where_column .= " and $table_name.$label_name =\"$process_month\" ";
			}
		}
		// $where_column_val = rtrim($where_column,',');
		return $where_column;
	}
	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 unix_convertion($excel_date){
		$unix_date  = ($excel_date - 25569) * 86400;
		$excel_date = 25569 + ($unix_date / 86400);
		$unix_date  = ($excel_date - 25569) * 86400;
		return $unix_date;
	}
	//SELECT QUERY BUILD FUNCTION
	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();
		// echo "<pre> table_qry_detail => $table_qry_detail";
		return $table_qry_rslt;
	}
	//INSERT QUERY BUILD FUNCTION
	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;
	}


	//prev view inputs
	public function get_previous_view($form_id){
		if($this->control_name === 'monthly_input'){
			$control_name = 'employees';
		}else{
			$control_name = $this->control_name;
		}
		$table_name   	  = "cw_".$control_name;
		$prime_table_id   = "prime_".$control_name."_id";
		$column_query = 'select GROUP_CONCAT("'.$table_name.'.",label_name) as label_name 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  = $column_rslt[0]->label_name;

		$from_query  = 'select '.$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;
	}
	//------------------------------- PAY STRUCTURE FUNCTION START ----------------------------------------------
	
	//FUNCTION FOR GET A PAY STRUCTURE FILTER BASED COLUMNS FROM PAY STRUCTURE SETTING TABLE 
	public function pay_add_filter_col_setting(){
		$pay_filter_column_qry    = 'select prime_form_id,field_type,pick_list,pick_list_type,view_name,pick_table,pick_display_value,pick_list_import,auto_prime_id,auto_dispaly_value,label_name,dependent_pick_list,dependent_pick_input,table_column1,table_column2,cw_pay_structure_settings.mandatory_column,cw_pay_structure_settings.filter_column from cw_form_setting inner join cw_pay_structure_settings on cw_pay_structure_settings.pay_struct_input = cw_form_setting.label_name where prime_module_id = "employees" and cw_form_setting.trans_status = 1 and cw_pay_structure_settings.trans_status = 1 and (cw_pay_structure_settings.mandatory_column = 1 or cw_pay_structure_settings.filter_column = 1) ORDER BY cw_pay_structure_settings.input_order ASC';
		// cw_pay_structure_settings.filter_column = 1 or 
		$pay_filter_column_data   = $this->db->query("CALL sp_a_run ('SELECT','$pay_filter_column_qry')");
		$pay_filter_column_rslt   = $pay_filter_column_data->result();
		$pay_filter_column_data->next_result();
		return $pay_filter_column_rslt;
	}
	
	//FUNCTION FOR GET A PAY STRUCTURE IMPORT BASED COLUMNS FROM PAY STRUUCTURE SETTING TABLE 
	public function pay_import_col_setting(){
		$pay_import_column_qry    = 'select prime_form_id,field_type,pick_list,pick_list_type,view_name,pick_table,pick_display_value,pick_list_import,auto_prime_id,auto_dispaly_value,label_name,dependent_pick_list,dependent_pick_input,table_column1,table_column2 from cw_form_setting inner join cw_pay_structure_settings on (cw_pay_structure_settings.pay_struct_input = cw_form_setting.label_name or cw_form_setting.label_name in ("professional_tax_location")) where prime_module_id = "employees" and cw_form_setting.trans_status = 1 and cw_pay_structure_settings.trans_status = 1 and (cw_pay_structure_settings.import_check_column = 1 or cw_form_setting.label_name in ("professional_tax_location")) ORDER BY cw_pay_structure_settings.prime_pay_structure_settings_id ASC';
		$pay_import_column_data   = $this->db->query("CALL sp_a_run ('SELECT','$pay_import_column_qry')");
		$pay_import_column_rslt   = $pay_import_column_data->result();
		$pay_import_column_data->next_result();
		return $pay_import_column_rslt;
	}

	public function pay_picklist_get_function($process,$pick_column_rslt,$type){
		foreach($pick_column_rslt as $setting){
			$prime_form_id      = (int)$setting->prime_form_id;
			$label_id           = $setting->label_name;
			$label_name         = ucwords($setting->view_name);
			$field_type         = (int)$setting->field_type;
			$pick_list_type     = (int)$setting->pick_list_type;
			$pick_list          = $setting->pick_list;
			$pick_table         = $setting->pick_table;
			$pick_display       = $setting->pick_display_value;
            $pick_list_import   = (int)$setting->pick_list_import;
			$auto_prime_id      = $setting->auto_prime_id;
			$auto_dispaly_value = $setting->auto_dispaly_value;
			
			$pick_result        = "";
			$pick_key           = "";
			$pick_val           = "";
			$final_pick         = "";
			//FOR PICKLIST
			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];
					
					if($label_id === "role"){
						$label_id  = "category";
					}
					if($process === "filter"){
						if($pick_display){
							$pick_list = "$pick_list_val_1,CONCAT_WS(\" ~ \", $pick_display) as $pick_list_val_2";
						}
						$whre_cond      = '';
						/*if($type === "onload"){
							
						}*/
						if($label_id === 'personal_code' || $label_id === 'position'){
							//WHERE CONDITION FOR EMPLOYEE MASTER AREA CONTROL BASED START 3NOV22
							if($label_id === 'personal_code'){
								if((int)$this->logged_user_role !== 1){
									$whre_cond  = 'and '.$pick_table.'.'.$label_id.' in ('.$this->logged_area_access.')';
								}
							}
							//WHERE CONDITION FOR EMPLOYEE MASTER AREA CONTROL BASED END 3NOV22
						}
						$pick_query  = "select $pick_list from $pick_table where trans_status = 1 $whre_cond";
						$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
						$pick_result = $pick_data->result();
						$pick_data->next_result();
						if($pick_result){
							//FOR FILTER AND IMPORT BASED ARRAY STRUCTURE FORMAT CREATE 
							$pick_key   = array_column($pick_result, $pick_list_val_1);
							$pick_val   = array_column($pick_result, $pick_list_val_2);
						}
					}else
					if($process === "import"){
						$pick_query      = "select $pick_list from $pick_table where trans_status = 1";
						$pick_data       = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
						$pick_result     = $pick_data->result();
						$pick_data->next_result();
						$pick_key        = array_column($pick_result, $pick_list_val_2);
						$pick_val        = array_column($pick_result, $pick_list_val_1);
						if($pick_list_import === 1){
							$pick_key    = array_column($pick_result, $pick_list_val_1);
							$pick_val    = array_column($pick_result, $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($process === "filter"){
						$pick_query = "select $pick_list_val_1,$pick_list_val_2 from $pick_table where $pick_list_val_3 = 1 ";
						$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
						$pick_result = $pick_data->result();
						$pick_data->next_result();
						if($pick_result){
							$pick_key   = array_column($pick_result, $pick_list_val_1);
							$pick_val   = array_column($pick_result, $pick_list_val_2);
						}
					}else
					if($process === "import"){
						$pick_query = 'select * from '.$pick_table.' where '.$pick_list_val_3.' = 1';
						$pick_data       = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
						$pick_result     = $pick_data->result();
						$pick_data->next_result();

						if($label_name === "role"){
							$label_name  = "category";
						}
						$pick_key        = array_column($pick_result, $pick_list_val_2);
						$pick_val        = array_column($pick_result, $pick_list_val_1);
						if($pick_list_import === 1){
							$pick_key    = array_column($pick_result, $pick_list_val_1);
							$pick_val    = array_column($pick_result, $pick_list_val_1);
						}
					}
				}
				
				if($pick_key && $pick_val){
					$final_pick = array_combine( $pick_key, $pick_val);	
					$final_pick = array("" => "---- $label_name ----") + $final_pick;
				}
			}else//FOR AUTO COMPLETE
			if($field_type === 9){
				if($type !== "onload"){
					$pick_display_val  = "CONCAT(".str_replace(",",'," - ",',$pick_display).") as auto_list_pick";
					$pick_query        = "select $auto_prime_id,$auto_dispaly_value,$pick_display_val 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){
					if($process === "filter"){
						$pick_key   = array_column($pick_result, $auto_prime_id);
						$pick_val   = array_column($pick_result, 'auto_list_pick');
						// $final_pick = array_combine( $pick_key, $pick_val);
					}else
					if($process === "import"){
						$pick_key   = array_column($pick_result, $auto_dispaly_value);
						$pick_val   = array_column($pick_result, $auto_prime_id);
						// $final_pick = array_combine( $pick_key, $pick_val);
					}
					if($pick_key && $pick_val){
						$final_pick = array_combine( $pick_key, $pick_val);
						$final_pick = array("" => "---- $label_name ----") + $final_pick;
					}
				}

			}
            $this->mi_pick_arr[$label_id]   = $final_pick;
		}
		return $this->mi_pick_arr;
	}
	
	//PAY STRUCTURE ON CHANGE DEPENDENT PICKLIST COLUMN GET FUNCTION
	public function dependent_pick_col_function($pick_data,$pick_input,$pay_pick_column_rslt){
		$depen_pay_pick_arr     = array();		
		foreach($pay_pick_column_rslt as $setting){
			$prime_form_id      = (int)$setting->prime_form_id;
			$label_id           = $setting->label_name;
			$label_name         = ucwords($setting->view_name);
			$pick_list_type     = (int)$setting->pick_list_type;
			$pick_list          = $setting->pick_list;
			$pick_table         = $setting->pick_table;
			$pick_display       = $setting->pick_display_value;
            $pick_list_import   = (int)$setting->pick_list_import;
			// echo "$label_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];
				$pick_query      = ""; 
				if($pick_display){
					$pick_list  = "$pick_list_val_1,CONCAT_WS(\" ~ \", $pick_display) as $pick_list_val_2";
				}   
                if($pick_input === "project_id" && $label_id === "project_id"){
                    $pick_query = "select $pick_list from $pick_table where trans_status = 1 and $pick_table.wbs_personal_area_id =\"$pick_data\"";
				}else
				if($pick_input === "wbs_element" && $label_id === "wbs_element"){
					$pick_query = "select $pick_list from $pick_table where trans_status = 1 and $pick_table.wbs_personal_area_id =\"$pick_data\"";
				}else
				if($pick_input === "network_id" && $label_id === "network_id"){
					$pick_query = "select $pick_list from $pick_table where trans_status = 1 and $pick_table.wbs_network_id =\"$pick_data\"";
				}else
				if($pick_input === "activity_no" && $label_id === "activity_no"){
					$pick_query = "select $pick_list from $pick_table where trans_status = 1 and $pick_table.act_wbs_id =\"$pick_data\"";
				}
				if($pick_query){
					// echo "pick_query::$pick_query";
					$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
					$pick_result = $pick_data->result();
					$pick_data->next_result();
					if($pick_result){
						//FOR FILTER AND IMPORT BASED ARRAY STRUCTURE FORMAT CREATE 
						$pick_key   = array_column($pick_result, $pick_list_val_1);
						$pick_val   = array_column($pick_result, $pick_list_val_2);
						// $depen_pay_pick_arr[$label_id]   = $final_pick;
						$depen_pay_pick_arr = array_combine( $pick_key, $pick_val);
					}
				}
            }
		}
		$depen_pay_pick_list      = "<option value = ''>---- Select List ----</option>";
		$pro_tax_arr              = array();
		foreach($depen_pay_pick_arr as $key => $val){
			$depen_pay_pick_list  .= "<option value = '$key'>$val</option>";
		}
		
		return $depen_pay_pick_list;
	}

	//------------------------------- PAY STRUCTURE FUNCTION END ----------------------------------------------
	//------------------------------- MONTHLY INPUT FMS AND TIME SHEET(FMS MAKER) FUNCTION START----------------

	public function mi_filter_col_setting(){
		$mi_filter_column_qry    = 'select prime_form_id,field_type,pick_list,pick_list_type,view_name,pick_table,pick_display_value,label_name,pick_list_import,auto_prime_id,auto_dispaly_value,cw_monthly_input_settings.mandatory_column,dependent_pick_list,dependent_pick_input,table_column1,table_column2 from cw_form_setting inner join cw_monthly_input_settings on cw_monthly_input_settings.map_column = cw_form_setting.label_name where prime_module_id = "employees" and cw_form_setting.trans_status = 1 and cw_monthly_input_settings.trans_status = 1 and cw_monthly_input_settings.filter_column = 1 ORDER BY cw_monthly_input_settings.prime_monthly_input_settings_id ASC';
        // and mandatory_column = 1
		$mi_filter_column_data   = $this->db->query("CALL sp_a_run ('SELECT','$mi_filter_column_qry')");
		$mi_filter_column_rslt = $mi_filter_column_data->result();
		$mi_filter_column_data->next_result();
		return $mi_filter_column_rslt;
	}
	public function mi_import_check_col_setting(){
		$mi_import_chk_col_qry    = 'select prime_form_id,field_type,pick_list,pick_list_type,view_name,pick_table,pick_display_value,label_name,pick_list_import,auto_prime_id,auto_dispaly_value,dependent_pick_list,dependent_pick_input,table_column1,table_column2 from cw_form_setting inner join cw_monthly_input_settings on cw_monthly_input_settings.map_column = cw_form_setting.label_name where prime_module_id = "employees" and cw_form_setting.trans_status = "1" and cw_monthly_input_settings.trans_status = "1" and cw_monthly_input_settings.import_check_column = 1 ORDER BY cw_monthly_input_settings.prime_monthly_input_settings_id ASC';
		$mi_import_chk_col_data   = $this->db->query("CALL sp_a_run ('SELECT','$mi_import_chk_col_qry')");
		$mi_import_chk_col_rslt   = $mi_import_chk_col_data->result();
		$mi_import_chk_col_data->next_result();
		return $mi_import_chk_col_rslt;
	}

	public function picklist_get_function($process,$pick_column_rslt){
		foreach($pick_column_rslt as $setting){
			$prime_form_id      = (int)$setting->prime_form_id;
			$label_id           = $setting->label_name;
			$label_name         = ucwords($setting->view_name);
			$field_type         = (int)$setting->field_type;
			$pick_list_type     = (int)$setting->pick_list_type;
			$pick_list          = $setting->pick_list;
			$pick_table         = $setting->pick_table;
			$pick_display       = $setting->pick_display_value;
            $pick_list_import   = (int)$setting->pick_list_import;
			$auto_prime_id      = $setting->auto_prime_id;
			$auto_dispaly_value = $setting->auto_dispaly_value;

			$pick_result        = "";
			$pick_key           = "";
			$pick_val           = "";
			$final_pick         = "";
			//FOR PICKLIST
			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];
					
					if($label_id === "role"){
						$label_id  = "category";
					}
					if($process === "filter"){
						if($pick_display){
							$pick_list = "$pick_list_val_1,CONCAT_WS(\" ~ \", $pick_display) as $pick_list_val_2";
						}
						if($label_id === "personal_code"){
							$area_access_where_cond =  ' and FIND_IN_SET(cw_sap_personal_area.personal_code, "'.$this->logged_area_access.'")';
						}else{
							$area_access_where_cond = "";
						}
						// if($label_id !== 'activity_no'){
							$pick_query = "select $pick_list from $pick_table where trans_status = 1 $area_access_where_cond";
							$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
							$pick_result = $pick_data->result();
							$pick_data->next_result();
						// }
						
						if($pick_result){
							//FOR FILTER AND IMPORT BASED ARRAY STRUCTURE FORMAT CREATE 
							$pick_key   = array_column($pick_result, $pick_list_val_1);
							$pick_val   = array_column($pick_result, $pick_list_val_2);
						}
					}else
					if($process === "import"){
						$pick_query      = "select $pick_list from $pick_table where trans_status = 1";
						$pick_data       = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
						$pick_result     = $pick_data->result();
						$pick_data->next_result();

						$pick_key        = array_column($pick_result, $pick_list_val_2);
						$pick_val        = array_column($pick_result, $pick_list_val_1);
						if($pick_list_import === 1){
							$pick_key    = array_column($pick_result, $pick_list_val_1);
							$pick_val    = array_column($pick_result, $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($process === "filter"){
						$pick_query = "select $pick_list_val_1,$pick_list_val_2 from $pick_table where $pick_list_val_3 = 1 ";
						$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
						$pick_result = $pick_data->result();
						$pick_data->next_result();
						if($pick_result){
							$pick_key   = array_column($pick_result, $pick_list_val_1);
							$pick_val   = array_column($pick_result, $pick_list_val_2);
						}
					}else
					if($process === "import"){
						$pick_query = 'select * from '.$pick_table.' where '.$pick_list_val_3.' = 1';
						
						$pick_data       = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
						$pick_result     = $pick_data->result();
						$pick_data->next_result();

						if($label_name === "role"){
							$label_name  = "category";
						}
						$pick_key        = array_column($pick_result, $pick_list_val_2);
						$pick_val        = array_column($pick_result, $pick_list_val_1);
						if($pick_list_import === 1){
							$pick_key    = array_column($pick_result, $pick_list_val_1);
							$pick_val    = array_column($pick_result, $pick_list_val_1);
						}
					}
				}
				if($pick_key && $pick_val){
					$final_pick = array_combine( $pick_key, $pick_val);	
					$final_pick = array("" => "---- $label_name ----") + $final_pick;
				}
			}else//FOR AUTO COMPLETE
			if($field_type === 9){
				$pick_display_val 	   = "CONCAT(".str_replace(",",'," - ",',$pick_display).") as auto_list_pick";
				$pick_query = "select $auto_prime_id,$auto_dispaly_value,$pick_display_val 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){
					if($process === "filter"){
						$pick_key   = array_column($pick_result, $auto_prime_id);
						$pick_val   = array_column($pick_result, 'auto_list_pick');
					}else
					if($process === "import"){
						$pick_key   = array_column($pick_result, $auto_dispaly_value);
						$pick_val   = array_column($pick_result, $auto_prime_id);
					}
					if($pick_key && $pick_val){
						$final_pick = array_combine( $pick_key, $pick_val);	
						$final_pick = array("" => "---- $label_name ----") + $final_pick;
					}
				}
			}
            $this->mi_pick_arr[$label_id]   = $final_pick;
		}
		return $this->mi_pick_arr;
	}
	
	//------------------ MONTHLY INPUT FMS AND TIME SHEET IMPORT FUNCTION END ----------------------- 
	public function check_import_error($excel_format_result,$total_rows,$excel_row_start,$sheet){
		$excel_rslt = json_decode(json_encode($excel_format_result),true);
		$excel_rslt = array_reduce($excel_rslt ?? [], function($result, $arr){	
		    $result[$arr['excel_line_column_name']] = $arr['excel_line_value'];
		    return $result;
		}, array());
		$form_query  = 'select prime_form_id,pick_table,pick_list,pick_display_value,pick_list_import,auto_prime_id,auto_dispaly_value,table_column1,table_column2,dependent_pick_input,label_name,field_type from cw_form_setting where trans_status = 1 and prime_module_id = "'.$this->control_name.'"';
		$form_data   = $this->db->query("CALL sp_a_run ('SELECT','$form_query')");
		$form_result = $form_data->result_array();
		$form_data->next_result();
		$label_wise_rslt = array_reduce($form_result ?? [], function($result, $arr){	
		    $result[$arr['label_name']] = $arr;
		    return $result;
		}, array());
		$status_row  	= 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;
			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;
				$depen_pick_list 		= (int)$excel_info->dependent_pick_list;
				$depen_pick_input 		= $excel_info->dependent_pick_input;
				$table_column1   		= $excel_info->table_column1;
				$table_column2   		= $excel_info->table_column2;
				$label_name 			= $excel_info->label_name;
				$prime_module_id 		= $excel_info->prime_module_id;
				$auto_prime_id 		    = $excel_info->auto_prime_id;
				$pick_display_value 	= $excel_info->pick_display_value;
				$auto_dispaly_value 	= $excel_info->auto_dispaly_value;
				$get_cell_value         = ucwords(trim($sheet->getCell("$excel_line_value$row")->getValue()));
                if($get_cell_value){
					// FOR PICKLIST CHECK
					if(($field_type === 5) || ($field_type === 7) || ($field_type === 9)){
						$get_pick_table = $label_wise_rslt[$label_name]['pick_table'];
						$depand_join 	= "";
						$depand_where 	= "";

						if((int)$depen_pick_list === 1){
							$depand_pick_input 		= $label_wise_rslt[$label_name]['dependent_pick_input'];
							$depand_field_type 		= (int)$label_wise_rslt[$depand_pick_input]['field_type'];
							$depand_pick_table 		= $label_wise_rslt[$depand_pick_input]['pick_table'];
							$depand_display_val 	= $label_wise_rslt[$depand_pick_input]['pick_display_value'];
							$depand_list_import 	= (int)$label_wise_rslt[$depand_pick_input]['pick_list_import'];
							$depand_pick_list 		= $label_wise_rslt[$depand_pick_input]['pick_list'];
							//dr start new
							$depand_auto_prime_id   = $label_wise_rslt[$depand_pick_input]['auto_prime_id'];
							$depand_auto_dispaly    = $label_wise_rslt[$depand_pick_input]['auto_dispaly_value'];
							//dr end new
							$depand_tbl1 			= $label_wise_rslt[$label_name]['table_column1'];
							$depand_tbl2 			= $label_wise_rslt[$label_name]['table_column2'];
							$depand_excel_val       = $excel_rslt[$depand_pick_input];
							if(!$depand_excel_val){
								$status_row['error']["$excel_line_value$row"] = "To import $label_name, $depand_pick_input data is mandatory.";
							}else{
								$depand_cell_value      = ucwords(trim($sheet->getCell("$depand_excel_val$row")->getValue()));
								//dr start new
								if($depand_field_type === 5){
									$depand_pick_list_val   = explode(",",$depand_pick_list ?? "");
									$depan_pick_list_val_1  = $depand_pick_list_val[0];
									$depan_pick_list_val_2  = $depand_pick_list_val[1];
	
									if((int)$depand_list_import === 1){
										$depand_where_col 	 =  $depan_pick_list_val_1;
									}else
									if((int)$depand_list_import === 2){
										$depand_where_col 	 =  $depan_pick_list_val_2;
									}
								}else
								if($depand_field_type === 9){
									$depand_where_col 	     =  $depand_auto_dispaly;
								}

								$depand_join 	= " inner join $depand_pick_table on $depand_pick_table.$depand_tbl1 = $get_pick_table.$depand_tbl2";
								$depand_where 	= " and $depand_pick_table.$depand_where_col = \"$depand_cell_value\"";

								$get_display_val   = $label_wise_rslt[$label_name]['pick_display_value'];
								$get_list_import   = $label_wise_rslt[$label_name]['pick_list_import'];
								//dr start new
								$get_auto_prime_id = $label_wise_rslt[$label_name]['auto_prime_id'];
								$get_auto_dispaly  = $label_wise_rslt[$label_name]['auto_dispaly_value'];

								if($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];

									if((int)$pick_list_import === 1){
										$where_col 	 =  $pick_list_val_1;
									}else
									if((int)$pick_list_import === 2){
										$where_col 	 =  $pick_list_val_2;
									}
								}else
								if($field_type === 9){
									$where_col 	     =  $auto_dispaly_value;
								}
                                //dr start end
								$pick_display_val 	= "$pick_table.".implode(",$pick_table.",explode(',', $pick_display_value ?? "") ?? []);

								$check_depand_query = "select $pick_display_val from $get_pick_table $depand_join where $get_pick_table.trans_status = 1 and $get_pick_table.$where_col = \"$get_cell_value\" $depand_where";
								$check_depand_info  = $this->db->query("CALL sp_a_run ('SELECT','$check_depand_query')");
								$check_depand_rslt  = $check_depand_info->result();
								$check_depand_info->next_result();
								if($check_depand_rslt){
									$insert_data	= $this->popup_check_data($pick_list_type,$pick_list,$pick_table,$pick_list_import,$get_cell_value,$field_type,$get_auto_prime_id,$get_auto_dispaly,$mandatory_field);
									// if($insert_data){
									// 	$status_row['error']["$excel_line_value$row"] 	= $insert_data;
									// }
									// return $insert_data;
								}else{
									$status_row['error']["$excel_line_value$row"] = 'No Data Available in Dependent Table.!Please Check it?.';
								}
							}
						}else{
							$insert_data	= $this->popup_check_data($pick_list_type,$pick_list,$pick_table,$pick_list_import,$get_cell_value,$field_type,$auto_prime_id,$auto_dispaly_value,$mandatory_field);
							// if($insert_data){
							// 	$status_row['error']["$excel_line_value$row"] 	= $insert_data;
							// }
							// return $insert_data;
						}
					}
				}
			}
		}
		return $status_row;
	}
public function popup_check_data($pick_list_type,$pick_list,$pick_table,$pick_list_import,$get_cell_value,$field_type,$auto_prime_id,$auto_dispaly_value,$mandatory_field){
	if($mandatory_field === 1){
		if((int)$field_type === 9){
			$pick_query = 'select '.$auto_prime_id.' from '.$pick_table.' where '.$auto_dispaly_value.' = "'.$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 === "cw_employees" && ($auto_prime_id === "employee_code" || $auto_prime_id === "emp_name")){
						$status_row['error']["$excel_line_value$i"] = 'Employee Invalid or Inactive';
				}else{
					$msg_line = "column invalid data is present please check it?";
					$status_row['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
				}
			}else{
				return true;
			}
		}else
		if((int)$field_type === 5){
			if((int)$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((int)$pick_list_import === 1){
					$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_1.' = "'.$get_cell_value.'"';
				}else
				if((int)$pick_list_import === 2){
					$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){
					if($pick_table === "cw_employees" && ($pick_list_val_1 === "employee_code" || $pick_list_val_2 === "emp_name")){
						$status_row['error']["$excel_line_value$i"] = 'Employee Invalid or Inactive';
					}else{
						$msg_line = "column invalid data is present please check it?";
						$status_row['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
					}
				}else{
					return true;
				}
			}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 count(*) as rslt_count 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->row();
				$pick_data->next_result();
				$pick_count  = (int)$pick_result->rslt_count;
				if((int)$pick_count === 0){
					$msg_line = "column invalid data is present please check it?";
					$status_row['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
				}else{
					return true;
				}
			}
		}
	}
	return $status_row;
}
	//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 field_type,label_name,pick_list,pick_table,prime_form_id 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";
		}
		$where_condition 	   = $this->get_role_based_picklist($picklist_table_rslt[$label_name]['prime_form_id'],$prime_module_id);
		
		$pick_query  = "";
		
		$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");
		//this input only for uds by dhinesh 25jul22
		$wbs_project_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();
		//DR CODE FOR WBS ELEMENT BASED PICKLIST VALUE FETCH(INPUT FOR ACTIVITY NO AND NETWORK ID)
		if($label_id === "wbs_element"){
			$form_wbs_query  = 'select * from cw_form_setting where cw_form_setting.label_name = "'.$label_id.'" and cw_form_setting.prime_module_id = "employees" and cw_form_setting.trans_status = 1';
			$form_wbs_data   = $this->db->query("CALL sp_a_run ('SELECT','$form_wbs_query')");
			$form_wbs_result = $form_wbs_data->result_array();
			$form_wbs_data->next_result();
			$auto_prime_id     = $form_wbs_result[0]['auto_prime_id'];		
			$where_cond        = "";
			if($auto_prime_id === 'prime_sap_wbs_id'){
				$where_cond  = 'prime_sap_wbs_id = "'.$label_value.'"';
			}else
			if($auto_prime_id === 'wbs_id'){
				$where_cond  = 'wbs_id = "'.$label_value.'"';
			}
			if($where_cond){
				$sap_wbs_query  = 'select prime_sap_wbs_id,wbs_id,wbs_project_id,wbs_network_id from cw_sap_wbs where '.$where_cond;
				$sap_wbs_data   = $this->db->query("CALL sp_a_run ('SELECT','$sap_wbs_query')");
				$sap_wbs_result = $sap_wbs_data->result_array();
				$sap_wbs_data->next_result();
				if($sap_wbs_result[0]){
					$label_value     = $sap_wbs_result[0]['wbs_id'];
					//this input only for uds by dhinesh 25jul22
					$wbs_project_id  = $sap_wbs_result[0]['wbs_project_id'];
					$wbs_network_id  = $sap_wbs_result[0]['wbs_network_id'];
				}
			}
		}	
		$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,'project_id' => $wbs_project_id,'network_id' => $wbs_network_id));
	}

	//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;
	}
	//DEPENDENT PRIME ID ARRAY FOR ALL DYNAMIC MODULE END
	//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;
	}
	//DR function for employees and employee onboard edit and view button hide and show
	public function master_data_show_fun($entry_flag){
		$whre_cond          = "";
		if($entry_flag === "c"){
			$whre_cond      = 'cw_employees.entry_flag = "'.$entry_flag.'" and cw_employees.sap_status in (1,3,4) and cw_employees.trans_status = 1';
		}else
		if($entry_flag === "e"){
			$whre_cond      = 'cw_employees.entry_flag = "'.$entry_flag.'" and cw_employees.sap_status not in (3,4,5) and cw_employees.trans_status = 1';
		}
		$emp_data_rslt_arr = "";
		// if((int)$this->logged_user_role !== 1){
			$emp_data_query    = 'SELECT cw_employees.prime_employees_id as prime_id FROM cw_employees WHERE '.$whre_cond;
			$emp_data_info     = $this->db->query("CALL sp_a_run ('SELECT','$emp_data_query')");
			$emp_data_result   = $emp_data_info->result_array();
			$emp_data_info->next_result();
			$emp_data_rslt_arr = array_reduce($emp_data_result ?? [], function($result, $arr){            
				$result[$arr['prime_id']] = $arr['prime_id'];
				return $result;
			}, array());
		// }
		return $emp_data_rslt_arr;
	}

	//DR CODE FOR wbs based pay struture position value get
	public function wbs_pay_struct(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$wbs_element       = $this->input->post('wbs_element');
		//pay structure select qry 
		$pay_position_qry  = 'SELECT cw_sap_position.position_code,cw_sap_position.position_name,cw_sap_position.prime_sap_position_id,gross FROM cw_pay_structure inner join cw_sap_position on cw_pay_structure.position = cw_sap_position.position_code WHERE cw_pay_structure.wbs_element = "'.$wbs_element.'" and cw_pay_structure.trans_status = 1 and cw_sap_position.trans_status = 1 and cw_pay_structure.status = 1 GROUP BY cw_sap_position.position_code'; 
		$pay_position_info = $this->db->query("CALL sp_a_run ('SELECT','$pay_position_qry')");
		$pay_position_rslt = $pay_position_info->result_array();
		$pay_position_info->next_result();
		
		$pos_list          = "<option value = ''>---- Select Position ----</option>";
		foreach($pay_position_rslt as $for){
			$prime_id           = $for['prime_id'];
			$position           = $for['position_code'];
			$position_name      = $for['position_name'];
			$gross              = $for['gross'];
			$pos_list          .= "<option value = '$position'>$position - $position_name - $gross</option>";
		}
		echo $pos_list;
	}

	//PERSONAL AREA SELECT QUERY FOR FETCH A PERSONAL AREA TO EMPLOYEE LOCATION INPUT
	public function emp_location_fetch(){
		$encString       = file_get_contents('php://input');
		$_POST           = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$personal_code   = $this->input->post('personal_code');
		//personal area select qry 
		$per_area_query  = 'select prime_sap_personal_area_id,personal_code,personal_name from cw_sap_personal_area where cw_sap_personal_area.personal_code = "'.$personal_code.'" and cw_sap_personal_area.trans_status = 1';
		$per_area_data   = $this->db->query("CALL sp_a_run ('SELECT','$per_area_query')");
		$per_area_rslt   = $per_area_data->result();
		$per_area_data->next_result();
		$personal_name   = $per_area_rslt[0]->personal_name;
		echo $personal_name;
	}
	public function get_bank_name(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$ifsc_prime_id   = $this->input->post('ifsc_prime_id');
		//personal area select qry 
		$bank_name_query  = 'select bank_name from cw_sap_ifsc where cw_sap_ifsc.ifsc_code = "'.$ifsc_prime_id.'" and cw_sap_ifsc.trans_status = 1';
		$bank_name_data   = $this->db->query("CALL sp_a_run ('SELECT','$bank_name_query')");
		$bank_name_rslt   = $bank_name_data->result();
		$bank_name_data->next_result();
		$bank_name   = $bank_name_rslt[0]->bank_name;
		if($bank_name){			
			echo json_encode(array('success' => TRUE, 'bank_name' => $bank_name));	
		}else{
			echo json_encode(array('success' => FALSE, 'bank_name' => $bank_name));	
		}
	}
	//filter autocomplete
	public function suggest_auto_filter(){
		$encString      = file_get_contents('php://input');
		$_POST          = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..'));
			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){
				$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_list      = $result->auto_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);		
	}
	
	//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' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$form_id                     = $this->input->post('view_id');
		$employee_code               = $this->input->post('employee_code');
		$aadhar_card_no              = $this->input->post('aadhar_card_no');
		$change_id_name              = $this->input->post('change_id');
		$change_inp_val              = $this->input->post('change_inp_val');
		$entry_flag                  = $this->input->post('entry_flag');
		$rslt =  $this->validate($aadhar_card_no,$employee_code,$change_id_name,$change_inp_val,$entry_flag);	
		$status  = $rslt['status'];
		$message = $rslt['message'];
		echo json_encode(array('success' => $status, 'message' => "$message","table_info" => $rslt['table_info']));
			exit(0);
	}

	public function validate($aadhar_card_no,$employee_code,$change_id_name,$change_inp_val,$entry_flag){
		$post_data                   = array();
		$post_data['aadhar_no']      = $aadhar_card_no;
		$post_data['employee_code']  = $employee_code;
		$post_data[$change_id_name]  = $change_inp_val;
		$post_data['entry_flag']     = $entry_flag;
		$post_json_data              = json_encode($post_data);
		$valid_unique                = $this->db->query("CALL sp_validate_unique ('$post_json_data')"); // DOUBT [MS 09-12-2024]
		$valid_unique_rslt           = $valid_unique->result_array();
		$valid_unique->next_result();

		if($valid_unique_rslt[0]){
			return array('status'=>FALSE,'message'=>"Unique Error..!Please View Unique Error Table?","table_info" => $valid_unique_rslt);
		}else{
			if($change_id_name === 'bank_account_number'){
				//Check vendor acc if bank validation			
				$bank_exist_qry = 'select vendor_code,vendor_name from cw_sap_vendor_account where vendor_acc_no = "'.$change_inp_val.'"';		
				$bank_exist_data    = $this->db->query("CALL sp_a_run ('SELECT','$bank_exist_qry')");
				$bank_exist_result  = $bank_exist_data->result();
				$bank_exist_data->next_result();
				if($bank_exist_result){
					$vendor_code = $bank_exist_result[0]->vendor_code;
					$vendor_name = $bank_exist_result[0]->vendor_name;
					return array('status'=>FALSE,'message'=>"Vendor Account Exist","table_info" =>[]);
				}else{
					return array('status'=>TRUE,'message'=>"Proceed..","table_info" =>[]);
				}
			}else{
				return array('status'=>TRUE,'message'=>"Proceed..","table_info" =>[]);
			}			
		}
	}
	
	//function for validate a unique fields via procedure
	public function unique_procedure_valid($post_json_data){
		$validation_sts_arr  = array();
		$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;
		}else{
			return $validation_sts_arr = array(1);
		}
	}	
	//EMPLOYEE PAY STYRUCTURE DETAILS GET
	public function emp_pay_struct_details(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$role              = $this->input->post('role');
		$personal_code     = $this->input->post('personal_code');
		$wbs_element       = $this->input->post('wbs_element');
		$position          = $this->input->post('position');
		$activity_no       = $this->input->post('activity_no');

		$pay_struct_qry    = 'select cw_sap_professional_tax.ptax_name,cw_pay_structure.from_date,cw_pay_structure.pf_limit,cw_pay_structure.esi_limit,cw_pay_structure.gross,cw_pay_structure.ear_gross,cw_pay_structure.pf_gross,cw_pay_structure.esi_gross,cw_pay_structure_line.field_type,wage_code,wage_name,hrms_field_name,amount,pf_applicable,esi_applicable,pt_applicable from cw_pay_structure inner join cw_pay_structure_line on cw_pay_structure.prime_pay_structure_id = cw_pay_structure_line.prime_pay_structure_id inner join cw_form_setting on (cw_form_setting.label_name = cw_pay_structure_line.hrms_field_name and cw_form_setting.prime_module_id = "employees") inner join cw_sap_professional_tax on cw_sap_professional_tax.ptax_code = cw_pay_structure.tax_location where cw_pay_structure.personal_code = "'.$personal_code.'" and cw_pay_structure.wbs_element = "'.$wbs_element.'" and cw_pay_structure.position = "'.$position.'" and cw_pay_structure.activity_no = "'.$activity_no.'" and cw_pay_structure_line.amount <> 0.00 and FIND_IN_SET('.$role.', cw_form_setting.field_for) and cw_pay_structure.category = "'.$role.'" and cw_pay_structure.status = 1 and cw_pay_structure.trans_status = 1 and cw_pay_structure_line.trans_status = 1 and cw_form_setting.trans_status = 1';
		$pay_struct_data   = $this->db->query("CALL sp_a_run ('SELECT','$pay_struct_qry')");
		$pay_struct_rslt   = $pay_struct_data->result_array();
		$pay_struct_data->next_result();

		if(!count($pay_struct_rslt ?? [])){
			echo json_encode(array('success' => FALSE, 'dom_data' => $dom_data));	
		}else{
			$pay_struct_arr    = array();

			$arr_format        = array_walk($pay_struct_rslt, function($v, $k) use (&$pay_struct_arr) {
				$pay_struct_arr[$v['field_type']][$v['hrms_field_name']] = $v;
			});
			
			//HTML CONTENT CREATE
			$limit_arr  = array("1" => "Yes","2" => "No",);
			$pay_tab    = "";
			$ear_tab    = "";
			$ded_tab    = "";
			$count      = 1;
			foreach($pay_struct_arr as $key => $val_arr){
				foreach($val_arr as $val){
					$ptax_name    = $val['ptax_name'];
					$from_date    = date("d-m-Y",strtotime($val['from_date']));
					$pf_limit     = $limit_arr[$val['pf_limit']];
					$esi_limit    = $limit_arr[$val['esi_limit']];
					$gross        = $val['gross'];
					$ear_gross    = $val['ear_gross'];
					$pf_gross     = $val['pf_gross'];
					$esi_gross    = $val['esi_gross'];
					$wage_name    = $val['wage_name'];
					$amount       = $val['amount'];
					if($key === "earnings"){
						$ear_tab    .= "<tr><td>$wage_name</td><td>$amount</td></tr>";
					}
					if($key === "deductions"){
						$ded_tab    .= "<tr><td>$wage_name</td><td>$amount</td></tr>";
					}
					if($count === 1){
						// style='padding: 8px;'
						$pay_tab      = "<div class='col-md-12 col-xs-12'><table class='table' style='font-weight: bold;'><tbody><tr><td style='text-align: center;'><span style='color:#f78223 !important;font-size:13px;font-weight: bold;'>Gross</span><br><span style='font-weight: bold;color:blue;'>$gross</span></td><td style='text-align: center;'><span style='color:#f78223 !important;font-size:13px;'>PTax Location</span><br>$ptax_name</td><td style='text-align: center;'><span style='color:#f78223 !important;font-size:13px;'>From Date</span><br>$from_date</td><td style='text-align: center;'><span style='color:#f78223 !important;font-size:13px;'>PF Gross</span><br>$pf_gross</td><td style='text-align: center;'><span style='color:#f78223 !important;font-size:13px;'>ESI Gross</span><br>$esi_gross</td><td style='text-align: center;'><span style='color:#f78223 !important;font-size:13px;'>PF Limit</span><br>$pf_limit</td><td style='text-align: center;'><span style='color:#f78223 !important;font-size:13px;'>ESI Limit</span><br>$esi_limit</td></tr></tbody></table></div>";
						// <td style='text-align: center;'><span style='color:#f78223 !important;font-size:13px;font-weight: bold;''>Ear Gross</span><br><span style='font-weight: bold;color:blue;'>$ear_gross</span></td>
					}
				}
				$count++;
			}
			
			$ear_tab    .= "<tr><td>Gross</td><td><span style='font-weight: bold;color:blue;'>$gross</td></tr>";
			// if($ear_tab !==  ""){
				$ear_tab    = "<table id = 'ear_tab' class = 'table table-hover'><thead class='thead-dark'><tr><th colspan = '2' style = 'text-align:center;'>Earnings</th></tr></thead><tbody>".$ear_tab."</tbody></table>";
			// }
			// if($ded_tab !==  ""){
				$ded_tab    = "<table id = 'ded_tab' class = 'table table-hover'><thead class='thead-dark'><tr><th colspan = '2' style = 'text-align:center;'>Deductions</th></tr></thead><tbody>".$ded_tab."</tbody></table>";
			// }
			$dom_data         = "$pay_tab<div class = 'col-md-6' id = 'ear_div'>$ear_tab</div><div class = 'col-md-6' id = 'ded_div'>$ded_tab</div>";

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

	//------------- DON'T DELETE -------------
	// public function project_id_fetch(){
	// 	$personal_code  = $this->input->post('personal_code');
	// 	// $search_month   = date("m-Y",strtotime("01-".$this->input->post('search_month')));
	// 	$process_month 	= $this->input->post("process_month");
	// 	//FOR ACTIVE PROJECT ONLY SHOULD SHOW IN PICKLIST
	// 	/*$start_date    = date("Y-m-d",strtotime('01-'.$search_month));
	// 	$end_date      = date("Y-m-t",strtotime($start_date)); */

	// 	$pro_id_qry     = 'SELECT pro_id,pro_desc FROM cw_sap_project INNER JOIN cw_transactions_fms on (cw_transactions_fms.personal_code = cw_sap_project.pro_personal_area_id and cw_transactions_fms.project_id = cw_sap_project.pro_id) WHERE cw_sap_project.pro_personal_area_id = "'.$personal_code.'" and cw_transactions_fms.personal_code = "'.$personal_code.'" and cw_transactions_fms.process_month = "'.$process_month.'" and cw_transactions_fms.trans_status = 1 and cw_sap_project.trans_status = 1 GROUP BY cw_sap_project.pro_id';
	// 	// and cw_sap_project.pro_start_date <= "'.$start_date.'" and cw_sap_project.pro_end_date >= "'.$end_date.'"

	// 	$pro_id_info    = $this->db->query("CALL sp_a_run ('SELECT','$pro_id_qry')");
	// 	$pro_id_rslt    = $pro_id_info->result_array();
	// 	$pro_id_info->next_result();
	// 	echo json_encode($pro_id_rslt);
	// }
	//DR CODE END FOR PROJECT ID FETCH BASED ON PERSONAL CODE 
	
	// ---------------- FOR TIME SHEET AND WAGE REGISTER ----------------
	//DR CODE START FOR WBS ELEMENT FILTER FETCH 29AUG22
	public function wbs_fetch(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$personal_code   = $this->input->post('personal_code');
		$project         = $this->input->post('project');
		$search_month    = $this->input->post('search_month');

		//FOR ACTIVE PROJECT ONLY SHOULD SHOW IN PICKLIST
		$start_date      = date("Y-m-d",strtotime('01-'.$search_month));
		$end_date        = date("Y-m-t",strtotime($start_date)); 

		$sel_wbs_qry     = 'select cw_sap_wbs.prime_sap_wbs_id,cw_sap_wbs.wbs_id,cw_sap_wbs.wbs_desc from cw_sap_wbs inner join cw_pay_structure on cw_pay_structure.wbs_element = cw_sap_wbs.wbs_id where cw_pay_structure.personal_code = "'.$personal_code.'" and cw_sap_wbs.wbs_personal_area_id = "'.$personal_code.'" and cw_sap_wbs.wbs_project_id = "'.$project.'" and date_format(cw_pay_structure.from_date, "%Y-%m") <= date_format(str_to_date("01-'.$search_month.'", "%d-%m-%Y") , "%Y-%m") and date_format(cw_pay_structure.to_date, "%Y-%m") >= date_format(str_to_date("01-'.$search_month.'", "%d-%m-%Y") , "%Y-%m") and cw_sap_wbs.trans_status = 1 and cw_pay_structure.trans_status = 1 and cw_sap_wbs.wbs_start_date <= "'.$start_date.'" and cw_sap_wbs.wbs_end_date >= "'.$end_date.'" GROUP BY cw_sap_wbs.prime_sap_wbs_id';
		// and cw_pay_structure.status = 1
		$sel_wbs_info    = $this->db->query("CALL sp_a_run ('SELECT','$sel_wbs_qry')");
        $sel_wbs_rslt    = $sel_wbs_info->result_array();
        $sel_wbs_info->next_result();

		echo json_encode($sel_wbs_rslt);
	}
	//DR CODE END FOR WBS ELEMENT FILTER FETCH 29AUG22

	public function emp_code_fetch(){
		$process_month     = $this->input->post("process_month");
		$personal_code     = $this->input->post("personal_code");
		$project_id        = $this->input->post("project_id");
		$wbs_element       = $this->input->post("wbs_element");
		$wbs_element_val   = implode('","',$wbs_element ?? []);

		//EMPLOYEE CODE GET QRY
		$emp_code_qry      = 'SELECT cw_transactions_fms.employee_code,cw_transactions_fms.emp_name from cw_transactions_fms where cw_transactions_fms.trans_status = 1 and cw_transactions_fms.process_month = "'.$process_month.'" and cw_transactions_fms.personal_code = "'.$personal_code.'" and cw_transactions_fms.project_id = "'.$project_id.'" and cw_transactions_fms.wbs_element in ("'.$wbs_element_val.'") GROUP BY cw_transactions_fms.employee_code';

		$emp_code_info     = $this->db->query("CALL sp_a_run ('SELECT','$emp_code_qry')");
        $emp_code_rslt     = $emp_code_info->result_array();
        $emp_code_info->next_result();

		echo json_encode($emp_code_rslt);
	}

	//ARREAR TRANSACTION DATA 
	public function query_arr_trans($id){
		$arr_qry           = 'SELECT cw_arr_info.arr_from_date as arr_from,cw_arr_info.arr_to_date as arr_to FROM cw_arr_info WHERE trans_status = 1 and prime_arr_info_id = "'.$id.'" '; 
		$arr_info          = $this->db->query("CALL sp_a_run ('SELECT','$arr_qry')");
		$arr_rslt          = $arr_info->result();
		$arr_info->next_result();
		return $arr_rslt;
	}

	public function validateMobileNumber($number) {
		return preg_match('/^[6-9](?!.*(\d)\1{4})\d{9}$/', $number) ? 1 : 0;
	}
	public function validateString($str) {
		return preg_match('/^(\$[a-zA-Z_][a-zA-Z0-9_]*|[a-zA-Z0-9]+)$/', $str) ? 1 : 0;
	}
	public function validateDOB($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 = '/^\d{2}\-\d{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){
		// echo $monthyear;
		return preg_match('/^(0[1-9]|1[0-2])(-|\/)\d{4}$/', $monthyear) ? 1 : 0;
	}
	public function validatetextarea($textarea){
		return preg_match('/^(?=.*[a-zA-Z0-9])[\w\s]+$/', $textarea) ? 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 ));
	}
	//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' => 'Invalid Request..','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_for !== "") && ($send_from !== "")){
			if(!file_exists("./upload_files/$send_from")){
				mkdir("./upload_files/$send_from", 0755, true);
				chmod("./upload_files/$send_from", 0755);
			}
			$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'];

			//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' =>"Invalid Request.."));
				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' => 'Invalid Request..','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);

			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' =>"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_SPECIAL_CHARS, FILTER_FLAG_NO_ENCODE_QUOTES);
				return htmlspecialchars($sanitized_string, ENT_QUOTES, 'UTF-8');
		}
	}
	//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' => 'Please try After sometime...'));
			//$this->session->sess_destroy();
			//redirect('login');
			exit(0);
			return false;		
		}	
	}
	 //DR GET WBS FROM PROJECT BASED FOR NEW ENTRY TABLE 5OCT22 START
	 public function get_wbs(){
        $encString         = file_get_contents('php://input');
        $_POST             = $this->cryptoDecrypt($encString);
        if(!$_POST){
            echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
            exit(0);
        }
        $project_id   = $this->input->post('project_id');
        $from_month   = $this->db->escape(date("Y-m-01",strtotime("01-" . $this->input->post('from_month'))));
        $to_month     = $this->db->escape(date("Y-m-01",strtotime("01-" . $this->input->post('to_month'))));
        if($project_id){
            $where_qry     = ' AND cw_sap_wbs.wbs_project_id = "'.$project_id.'"  ';
        }
        //pay structure select qry  AND cw_sap_wbs.wbs_project_id = '$project_id'
        $get_wbs_info      = $this->db->query("CALL sp_a_run ('SELECT','SELECT DISTINCT cw_sap_wbs.wbs_id,cw_sap_wbs.prime_sap_wbs_id,cw_sap_wbs.wbs_desc FROM cw_sap_wbs JOIN cw_transactions_fms ON cw_sap_wbs.wbs_id = cw_transactions_fms.wbs_element WHERE cw_sap_wbs.trans_status = 1 AND DATE_FORMAT(STR_TO_DATE(CONCAT(\"01-\",cw_transactions_fms.transactions_month),\"%d-%m-%Y\"),\"%Y-%m-%d\") BETWEEN '$from_month' AND '$to_month' $where_qry ')");
        $get_wbs_rslt = $get_wbs_info->result_array();
        $get_wbs_info->next_result();
        $wbs_list           = "<option value = ''>----Select Project ----</option>";
        foreach($get_wbs_rslt as $for){
            $prime_id       = $for['prime_sap_wbs_id'];
            $wbs_id         = $for['wbs_id'];
            $wbs_desc       = $for['wbs_desc'];
            $wbs_list      .= "<option data-value = '$wbs_id' value = '$wbs_id'> $wbs_desc</option>";
        }
        echo $wbs_list;
    }
}
?>