MOON
Server: Apache
System: Linux nserver.cafsindia.com 4.18.0-553.104.1.lve.el8.x86_64 #1 SMP Tue Feb 10 20:07:30 UTC 2026 x86_64
User: cafsindia (1002)
PHP: 8.2.30
Disabled: NONE
Upload Files
File: //home/cafsindia/cloud_cafsinfotech_in/application/controllers/Action_controller.php
<?php
/**********************************************************
	   Filename: Action Controller
	Description: Action Controller for all dynamic module controller.
		 Author: udhayakumar Anandhan
	 Created on: ?30 ?December ?2019
	Reviewed by:
	Reviewed on:
	Approved by:
	Approved on:
	-------------------------------------------------------
	Modification Details
	Changed by:
	Change Info:
	-------------------------------------------------------
***********************************************************/
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once("Secure_Controller.php");
ini_set("memory_limit","2048M");
ini_set("max_execution_time","60000");
require('./application/libraries/dompdf/autoload.inc.php');
use Dompdf\Dompdf;
use DOMDocument;
use ZipArchive;
abstract class Action_controller extends Secure_Controller{	
	public $control_name;
	public $logged_id;
	public $logged_role;
	public $logged_consultancy;
	public $logged_dept;
	public $prime_id;
	public $prime_table;
	public $leave_financial_info;
	public $financial_info;
	public $fanf_header_info;
	public $base_query            = "" ;
	public $quick_link            = array();
	public $table_head            = array();
	public $view_info             = array();
	public $form_info             = array();
	public $rowset_form_info      = array();
	public $role_condition;       
	public $select_query          = "";
	public $view_select           = "";
	public $all_pick              = array();
	public $master_pick           = array();
	public $components            = array();
	public $emp_pick_arr          = array();
	public $formula_result        = array();
	public $role_based_condition  = array();
	public $email_setting 		  = array();
	public $freeze_count 		  = array();
	public $password_encrypt 	  = array();
	public $category_month_day 	  = array();	
	public $general_setting_info  = array();
	public $company_info          = array();
	public $bind_info             = array();
	public $condition_info        = array();
	public $get_map_arr           = array();
	public $form_arr              = array();
	public $control_whr_cond;
	public $order_by_cond;
	
	private $db_conn_id;
	public $module_sts;
	public $module_id;
	public $condition_list   = array();
	public $session_list     = array();
	public $pick_list        = array();
	public $depen_auto_list  = array();
	public $form_condition_list = array();
	public $row_view_list    = array();

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

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

	public function __construct($module_id = NULL){
		require('./phpmailer/class.phpmailer.php');
		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->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->view_select        = "$this->prime_table.$this->prime_id,";

		/* UDY NEED TO GET CALIRITY */
		if($this->formula_allow[$module_id]){
			echo $this->create_formula_file();
			$this->load->model('Formula_model');	
			$this->load->model('Hr_methods_model');
			
		}
	}
	
	/******************** UDY _START **********************/	
	public function run_multi_qry($qry){
		/* 1. NEED TO VALID is array  */
		$sts       = false;
		$msg       = "no data processed";
		$data      = [];
		$final_qry = implode(';',array_column($qry,'qry')).";";
		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){
			$final_rslt = array_reduce($qry, function($result, $arr){         
				$result[$arr['return']] = $arr['rslt'];
				return $result;
			}, array());
		}
		return json_decode(json_encode(array("sts"=>$sts,"msg"=>$msg,"rslt"=>$final_rslt)));			
    }
		
	public function page_info(){
		$this->control_whr_cond  = ""; 
		// UDY TEMP NNED TO REMOVE
		//EMPLOYEE MASTER BASED TABLE INPUTS		
		if($this->alias_control[$this->control_name]){
			$control_name = $this->alias_control[$this->control_name];
			//FOR MONTHLY INPUT 
			if($this->mi_base[$this->control_name]){
				$this->control_whr_cond  = ' and (earn_month_check = "1" OR deduction_month_check = "1")'; 
			}
			$emp_custom_join    = "";
			$emp_custom_whr     = "";
			
		}else{
			$control_name = $this->control_name;
		}	
		$order_by = ' ORDER BY input_for,field_sort asc';
		//FOR ONBOARD
		if($this->control_name === 'employee_onboard'){
			$this->control_whr_cond = ' and (cw_form_setting.onboard_order != "" and cw_form_setting.onboard_order != 0)';
			$order_by               = ' ORDER BY onboard_order asc';
		}else
		if($this->mi_base[$this->control_name]){//FOR MONTHLY INPUT
			$order_by               = ' ORDER BY monthly_input_sort asc';
		}		
		
		// UDY TEMP NEED TO REMOVE		
		$pro_qry     = [];
		$pro_qry[]   = array("return"=>"quicklink","qry"=>'select quicklink from cw_modules  where module_id = "'.$this->control_name.'"');
		//FORM INFO QUERY FOR EMPLOYEE SELF AND AUDIT TRIAL AND OTHERS BASED CONDITION
		//IF CONDTION ONLY FOR EMPLOYEE SELF PORTAL SEARCH
		if($this->control_name === "employee_self_portal"){
			$control_name      = "audit_trial";
		}
		// if($this->control_name !== "employee_self_portal"){
			$pro_qry[]   = array("return"=>"form_info","qry"=>'select * from cw_form_setting where prime_module_id = "'.$control_name.'" and field_show = "1" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",user_right_for)'.$this->control_whr_cond.$order_by);
		// }else{
		// 	$pro_qry[]   = array("return"=>"form_info","qry"=>'select cw_form_setting.* from cw_custom_design inner join cw_form_setting on cw_form_setting.label_name=cw_custom_design.label_name and cw_form_setting.prime_module_id=cw_custom_design.prime_module_id and cw_form_setting.input_for=cw_custom_design.input_for where cw_custom_design.prime_module_id="'.$control_name.'" and cw_custom_design.input_view in (1,2,3) and cw_form_setting.trans_status = "1" ORDER BY cw_form_setting.input_for,cw_form_setting.field_sort asc');
		// }

		$pro_qry[]   = array("return"=>"freeze_list","qry"=>'select left_freeze,right_freeze from cw_modules where module_id = "'.$this->control_name.'" and trans_status = "1"');
		$pro_qry[]   = array("return"=>"condition_list","qry"=>'select query_list_id,pick_where_condition from cw_pick_base_search where pick_module_id = "'.$this->control_name.'" and 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"');
		//Company Information qry
		$pro_qry[]   = array("return"=>"company_info","qry"=>'select * from cw_company_information where cw_company_information.trans_status = 1');
		//financial year qry
		$pro_qry[]   = array("return"=>"financial_info","qry"=>'SELECT prime_financial_setting_id,start_date,end_date from cw_financial_setting where set_as_default_financial_year = 1 and trans_status = "1"');
		
		// echo "<pre>";
		// print_r($pro_qry);die;
		if(count($pro_qry) > 0){
			$page_info_rslt         = $this->run_multi_qry($pro_qry);
		
			if(!$page_info_rslt->sts){
				$this->module_sts   = false;
			}else{
				
				$condition_rslt     = [];
				$condition_list     = json_decode(json_encode($page_info_rslt->rslt->condition_list),true);
				if(count($condition_list) > 0){
					$condition_key  = array_column($condition_list, 'query_list_id');
					$condition_val  = array_column($condition_list, 'pick_where_condition');
					$condition_rslt = array_combine($condition_key, $condition_val);
				}

				$table_info         = [];
				$filter_info        = [];
				$pro_pick_list      = [];

				foreach($page_info_rslt->rslt->form_info as $key => $value){
					$field_type       = (int)$value->field_type;
					$table_show       = (int)$value->table_show;
					$search_show      = (int)$value->search_show;
					$input_view_type  = (int)$value->input_view_type;	

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

				if(count($pro_pick_list) > 0){
					$this->get_pick_list_qry($pro_pick_list);
					//ONLY FOR TIME SHEET
					if($this->mi_base[$this->control_name]){
						$this->get_import_pick_list_qry($pro_pick_list);
					}
				}
			}
		}
	}
	
	public function search_info(){
		$this->control_whr_cond  = ""; 
		// UDY TEMP NNED TO REMOVE
		//EMPLOYEE MASTER BASED TABLE INPUTS		
		if($this->alias_control[$this->control_name]){
			$control_name = $this->alias_control[$this->control_name];
			//FOR MI AND MI FMS AND TIME SHEET
			if($this->mi_base[$this->control_name]){
				$this->control_whr_cond  = ' and (earn_month_check = "1" OR deduction_month_check = "1")'; 
			}
		}else{
			$control_name = $this->control_name;
		}	
		$order_by = ' ORDER BY input_for,field_sort asc';
		//FOR ONBOARD
		if($this->control_name === 'employee_onboard'){
			$this->control_name     = 'employees';
			$this->control_whr_cond = ' and (cw_form_setting.onboard_order != "" and cw_form_setting.onboard_order != 0)';
			$order_by               = ' ORDER BY onboard_order asc';
		}else//FOR MI AND MI FMS AND TIME SHEET
		if($this->mi_base[$this->control_name]){
			$order_by               = ' ORDER BY monthly_input_sort asc';
		}		
		// UDY TEMP NNED TO REMOVE
		$pro_qry   = [];
		//FORM INFO QUERY FOR EMPLOYEE SELF AND AUDIT TRIAL AND OTHERS BASED CONDITION
		//IF CONDTION ONLY FOR EMPLOYEE SELF PORTAL SEARCH
		if($this->control_name === "employee_self_portal"){
			$control_name      = "audit_trial";
		}
		// $this->control_name !== "employee_self_portal" && 
		// if($this->control_name !== "audit_trial"){
			$pro_qry[]   = array("return"=>"form_info","qry"=>'select * from cw_form_setting where prime_module_id = "'.$control_name.'" and field_show = "1" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",user_right_for)'.$this->control_whr_cond.$order_by);
		// }else{
		// 	$pro_qry[]   = array("return"=>"form_info","qry"=>'select cw_form_setting.* from cw_custom_design inner join cw_form_setting on cw_form_setting.label_name=cw_custom_design.label_name and cw_form_setting.prime_module_id=cw_custom_design.prime_module_id and cw_form_setting.input_for=cw_custom_design.input_for where cw_custom_design.prime_module_id="'.$control_name.'" and cw_custom_design.input_view in (1,2,3) and cw_form_setting.trans_status = "1" ORDER BY cw_form_setting.input_for,cw_form_setting.field_sort asc');
		// }
		
		$pro_qry[] = array("return"=>"role_condition_list","qry"=>'select where_condition from cw_form_table_search where query_module_id = "'.$this->control_name.'" and 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"');
		//Company Information qry
		$pro_qry[] = array("return"=>"company_info","qry"=>'select * from cw_company_information where cw_company_information.trans_status = 1');
		//financial year qry
		// $pro_qry[]   = array("return"=>"financial_info","qry"=>'SELECT prime_financial_setting_id,start_date,end_date from cw_financial_setting where set_as_default_financial_year = 1 and trans_status = "1"');
		// echo "<pre>";
		// print_r($pro_qry);die;
		if(count($pro_qry) > 0){
			$search_info_rslt = $this->run_multi_qry($pro_qry);
			if(!$search_info_rslt->sts){
				$this->module_sts = false;
			}else{
				$this->form_info      = $search_info_rslt->rslt->form_info;
				$this->session_list   = $search_info_rslt->rslt->session_list;
				//BASIC SEARCH TABLE ROLE BASE CONDITION START
				$role_condition_list  = $search_info_rslt->rslt->role_condition_list[0];
				$this->company_info   = $search_info_rslt->rslt->company_info;
				$this->financial_info = $search_info_rslt->rslt->financial_info;
				$where_condition      =  "";
				if($role_condition_list->where_condition){
					$where_condition           = $role_condition_list->where_condition;				
					$where_condition           = str_replace('^','"',$where_condition);
					foreach($this->session_list as $session_val){
						$session_value 	       = $session_val->session_value;
						$saved_session_val     = $this->session->userdata($session_value);
						$exist_val             = "@".$session_value."@";
						$where_condition       = str_replace($exist_val,$saved_session_val,$where_condition);
					}
				}
				$where_condition  = str_replace(',','","',$where_condition);
				$this->role_condition    = $where_condition;
				//BASIC SEARCH TABLE ROLE BASE CONDITION END

				$table_info        = [];
				$filter_info       = [];
				$pro_pick_list     = [];
				foreach($this->form_info as $key => $value){
					$table_show         = (int)$value->table_show;
					$search_show        = (int)$value->search_show;
					$field_type         = (int)$value->field_type;	
					$input_view_type    = (int)$value->input_view_type;	
					
					if($this->mi_base[$this->control_name]){
						if($input_view_type !== 3){
							$table_info[$key]   = $value;
						}
						if(($field_type === 5) || ($field_type === 7) || ($field_type === 9)){
							$pro_pick_list[$key]  = $value;
						}
					}else{
						if($table_show === 1){
							if($input_view_type !== 3){
								$table_info[$key]   = $value;
							}
							if(($field_type === 5) || ($field_type === 7) || ($field_type === 9)){
								$pro_pick_list[$key]  = $value;
							}
						}
						if($search_show === 1){
							$filter_info[$key]  = $value;
						}
					}
				}
				$this->table_head           = $table_info;
				$this->fliter_list          = $filter_info;
				
				$select_key              = array_column($this->table_head, "label_name");
				$this->select_query     .= implode(",",$select_key);

				//PICKLIST & AUTOCOMPLETE DATA
				if(!$this->mi_base[$this->control_name]){
					if(count($pro_pick_list) > 0){
						$this->get_pick_list_qry($pro_pick_list);
						//ONLY FOR TIME SHEET
						// if($this->mi_base[$this->control_name]){
						// 	$this->get_import_pick_list_qry($pro_pick_list);
						// }
					}
				}
			}	
		}
	}

	public function view_info($prime_id){
		// echo $this->control_name;
		if($this->alias_control[$this->control_name]){
			$control_name = $this->alias_control[$this->control_name];
		}else{
			$control_name = $this->control_name;
		}	
		// echo $control_name;
		$order_by                = ' ORDER BY input_for,field_sort asc';
		//UDS ONBOARD query
		if($this->control_name === 'employee_onboard'){
			$this->control_whr_cond = ' and (cw_form_setting.onboard_order != "" and cw_form_setting.onboard_order != 0)';
			$order_by = ' ORDER BY onboard_order asc';
		}	

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

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

		$pro_qry[]   = array("return"=>"condition_list","qry"=>'select query_list_id,pick_where_condition from cw_pick_base_search where pick_module_id = "'.$this->control_name.'" and 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) 
		if($this->control_name === "employee_self_portal"){
			$pro_qry[]   = array("return"=>"form_condition_list","qry"=>'select * from cw_form_condition_formula where cond_module_id = "employees" and trans_status = "1" and FIND_IN_SET("'.$this->logged_role.'",condition_for)');
		}else{
			$pro_qry[]   = array("return"=>"form_condition_list","qry"=>'select * from cw_form_condition_formula where cond_module_id = "'.$this->control_name.'" and trans_status = "1" and FIND_IN_SET("'.$this->logged_role.'",condition_for)');
		}
		//Get Company Info
		$pro_qry[]   = array("return"=>"company_info","qry"=>'select * from cw_company_information where cw_company_information.trans_status = 1');
		//DHR COMMAND FOR FORM CONDITION LIST (IT ADD FROM LAST) 	
		//financial year qry
		$pro_qry[]   = array("return"=>"financial_info","qry"=>'SELECT prime_financial_setting_id,start_date,end_date from cw_financial_setting where set_as_default_financial_year = 1 and trans_status = "1"');

		// echo "<pre>";
		// print_r($pro_qry);die;
		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);				
				foreach($role_based_list as $key => $condition) {
					$role_based_condition[$condition['user_condition_type']] = $condition['input_columns'];
				}
				$pro_pick_list         = [];
				$depen_auto_pick_list  = [];
				foreach($view_info_rslt->rslt->form_info as $key => $value){
					$field_type       = (int)$value->field_type;
					$field_show       = (int)$value->field_show;
					$depen_pick_list  = (int)$value->dependent_pick_list;		
					$label_id         = $value->label_name;
					$input_view_type  = (int)$value->input_view_type;
					if($field_show === 1){
						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;
						}*/
					}
				}
				//VIEW INFO LIST
				$this->view_info            = $view_info_rslt->rslt->view_info;
				$this->form_info            = $view_info_rslt->rslt->form_info;
				$this->formula_result       = $view_info_rslt->rslt->formula_result;
				$this->role_based_condition = $role_based_condition;
				$this->condition_list       = $condition_rslt;
				$this->session_list         = $view_info_rslt->rslt->session_list;
				$this->company_info         = $view_info_rslt->rslt->company_info;
				$this->financial_info       = $view_info_rslt->rslt->financial_info;

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

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

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

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

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

			if($field_isdefault === 1){	 // UDY NEED CHECK
				if(($field_type === 5) || ($field_type === 7)){
					if($pick_list_type === 1){
						$pick_list_val       = explode(",",$pick_list);
						$pick_list_val_1     = $pick_list_val[0];
						$pick_list_val_2     = $pick_list_val[1];
						$imp_pick_list_val_1 = $pick_list_val_1;
						$imp_pick_list_val_2 = $pick_list_val_2;
						if($pick_display){
							$pick_list = "$pick_list_val_1,CONCAT_WS(\" ~ \", $pick_display) as $pick_list_val_2";
							$pick_qry  = 'select '.$pick_list.' from '.$pick_table.' where trans_status = 1 '.$where_condition;
							$pick_qry  = rtrim($pick_qry," ");
							$pro_qry[] = array("return"=>$label_id,"qry"=>$pick_qry,"pro_info"=>array('prime_form_id' => $prime_form_id,'label_id' => $label_id,'label_name' => $label_name,'field_type' => $field_type,'pick_list_type' => $pick_list_type,'pick_list_val_1' => $pick_list_val_1,'pick_list_val_2' => $pick_list_val_2,'table_show' => $table_show,'search_show' => $search_show,'field_isdefault' => $field_isdefault,));
						}
					}else
					if($pick_list_type === 2){
						$pick_list_val_1 = $pick_table."_id";
						$pick_list_val_2 = $pick_table."_value";
						$pick_list_val_3 = $pick_table."_status";
						$pick_qry        = 'select '.$pick_list_val_1.','.$pick_list_val_2.' from '.$pick_table.' where '.$pick_list_val_3.' = 1'. $where_condition;
						$pick_qry        = rtrim($pick_qry," ");
						$pro_qry[]       = array("return"=>$label_id,"qry"=>$pick_qry,"pro_info"=>array('prime_form_id' => $prime_form_id,'label_id' => $label_id,'label_name' => $label_name,'field_type' => $field_type,'pick_list_type' => $pick_list_type,'pick_list_val_1' => $pick_list_val_1,'pick_list_val_2' => $pick_list_val_2,'table_show' => $table_show,'search_show' => $search_show,'field_isdefault' => $field_isdefault,));
					}
				}else
				if($field_type === 9){
					$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'];
							$pick_list_val_1    = $pro_info['pick_list_val_1'];
							$pick_list_val_2    = $pro_info['pick_list_val_2'];
							// if($pick_list_type === 1){
								$pick_key   = array_column($list_info, $pick_list_val_1);
								$pick_val   = array_column($list_info, $pick_list_val_2);
								$final_pick = array_combine( $pick_key, $pick_val);
								if($final_pick){
									$final_pick = array("" => "---- $label_name ----") + $final_pick;
								}
							// }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

						$field_type            = (int)$cond_info[0]['field_type'];
						$label_name            = $pro_info['label_name'];
						$prime_cond_id         = $pro_info['prime_cond_id'];
						$cond_module_id        = $pro_info['cond_module_id'];
						$condition_label_name  = $pro_info['condition_label_name'];
						$condition_type        = (int)$pro_info['condition_type'];
						$condition_check_form  = $pro_info['condition_check_form'];
						$condition_bind_to     = $pro_info['condition_bind_to'];

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

					}
					
					if($on_blur_inputs){
						$on_blur_input = rtrim($on_blur_inputs,',');
						$on_blur_input = str_replace(",",",#",$on_blur_input);
						$on_blur_input = "#".$on_blur_input;
						if($check_input){
							$check_input .= ",$on_blur_input";
						}else{
							$check_input .= "$on_blur_input";
						}
					}
					
					$send_for  = implode(",",$condition_check_form);
					$send_data = "prime_cond_id:$prime_cond_id,for_input:'$send_for',";
					foreach($condition_check_form as $check_form){
						$send_data .= "$check_form:$('#$check_form').val(),";
					}
					$send_data = "{".rtrim($send_data,',')."}";
					
					//BIND VALUE FROM DATABASE TABLE
					if($condition_type === 1){
						if($on_bind_input){
							$fill_input = "";
							foreach($condition_bind_to as $bind_to){
								$fill_val    = "ui.item.".$bind_to;
								$fill_input .= "$('#$bind_to').val($fill_val);\n";
							}
							$send_url     = site_url("$this->control_name/bind_autocomplete_suggest");
							$load_script .= "$('$on_bind_input').autocomplete({
												source: function(request, response) {
													$.getJSON('$send_url',{term:request.term, prime_cond_id:$prime_cond_id },response);
												},
												minChars:2,
												autoFocus: true,
												delay:10,
												appendTo: '.modal-content',
												select: function(e, ui) {
													$fill_input
													return false;
												}
											});\n";
						}
						if($on_change_input){
							$fill_input = "";
							foreach($condition_bind_to as $bind_to){
								$fill_val    = "rslt[0].".$bind_to;
								$fill_input .= "$('#$bind_to').val($fill_val);\n";
							}
							
							$send_url  = site_url("$this->control_name/bind_change_suggest");
							$load_script .= "$('$on_change_input').change(function(){
												var isValid = true;
												$('$on_change_input').each(function() {
												if ($(this).val() === '') {
													isValid = false;
													$(this).addClass('error');
												}else{
													$(this).removeClass('error');
												}
												});
												if(isValid){
													$.ajax({
														type: 'POST',
														url: '$send_url',
														data:$send_data,
														success: function(data) {
															var rslt = JSON.parse(data);
															$fill_input
														}
													});
												}
											});\n";
						}
					}else  //FOR WRITE CONDITIONS TYPE
					if($condition_type === 2){
						$fill_input = "";
						foreach($condition_bind_to as $bind_to){
							$fill_val    = "rslt.".$bind_to;
							$fill_input .= "$('#$bind_to').val($fill_val);\n $('#$bind_to').trigger('change');";
						}
						$send_url  = site_url("$this->control_name/calculation_suggest");

						//CODE FOR JS FUNCTION ADD
						$function_info = "function $condition_label_name(input_id){
											var isValid = true;
											$('#'+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:$send_data,
													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) {
												var input_id = $(this).attr('id');
												$condition_label_name(input_id);
											});\n";
						}
						if($on_change_input){
							$load_script .= "$('$on_change_input').change(function(){
												var input_id = $(this).attr('id');
												$condition_label_name(input_id);
											});\n";
						}
						if($on_blur_input){
							$load_script .= "$('$on_blur_input').blur(function(){
												var input_id = $(this).attr('id');
												$condition_label_name(input_id);
											});\n";
						}
						$load_script .= "\n$function_info\n";
					}
					
				}
			}
		}
				
		$load_script .= "\nlet status      = document.getElementsByClassName('modal-title')[0];
            window.addEventListener('load', function(e){
                if (navigator.onLine) {
                    //status.innerHTML = 'User is online';
                    status.classList.add('success');
                    status.classList.add('success');
                } else {
                    status.innerHTML = 'Please Check Your Internet Connection...';
                    status.classList.remove('success');
                    status.classList.add('internet_modal_error');                    
                }
            }, false);            
            window.addEventListener('online', function(e){
               // status.innerHTML = 'User is back online';
                status.classList.remove('internet_modal_error');
                status.classList.add('success');
                location.reload();
            }, false);            
            window.addEventListener('offline', function(e){
                status.innerHTML = 'Please Check Your Internet Connection...';
                status.classList.remove('success');
                status.classList.add('internet_modal_error');
            }, false);\n
            $('.select2').on('select2:select', function(e){
				 $(this).focus();
			     e.preventDefault(); 
			});\n";
		if($load_script){
			$this->form_condition_list[] = $load_script;
		}		
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	//PROVIDE BASE DATA FOR MODULE
	public function collect_base_info(){
		require('./phpmailer/class.phpmailer.php');
		$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->prime_id          = "prime_".$this->control_name."_id";
		$this->prime_table       = $this->db->dbprefix($this->control_name);
		$this->base_query        = "select @SELECT@ from $this->prime_table";
		$this->select_query      = "$this->prime_table.$this->prime_id,";
		if($this->control_name === "employee_log_report"){
			$this->control_name  = "employees";
		}
		$this->get_quick_link();
		$this->get_table_head();		
		$this->get_view_info();
		$this->get_form_info();
		$this->get_leave_financial_details();		
		// $this->get_financial_year();
		$this->get_role_condition();
		$this->get_query_and_drop();
		$this->get_condition();
		$this->get_financial_year();
		$this->coloring_label();
		$this->role_based_condition();
		$this->get_freeze_count();
		$this->get_password_encrypt();
		$this->get_email_setting();
		$this->get_table_info();
		$this->get_fandf_header_info();
		$this->category_month_day();
		$this->general_setting_info();
		$this->company_info();
		$this->get_bind_info();
		$this->column_mapping();
		$this->get_tos_active_salary_date();
		if($this->control_name === 'request' || $this->control_name === 'direct_leave_entry' || $this->control_name === 'approval'){
			$this->get_emp_data();
		}
	}
	
	/* ==============================================================*/
	/* =================== BASE FUNCTIONS - START ===================*/
	/* ==============================================================*/
	public function get_bind_info(){
		$input_query  = 'select * from cw_form_bind_input where trans_status = 1';
		$input_data   = $this->db->query("CALL sp_a_run ('SELECT','$input_query')");
		$input_result = $input_data->result_array();
		$input_data->next_result();
		$input_result    = array_reduce($input_result, function($result, $arr){			
	    	$result[$arr['input_cond_id']][] = $arr;
	    	return $result;
		}, array());

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

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

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

	// PROVIDE QUICK LINK LIST VIEW
	public function get_quick_link(){
		$link_query       = 'select quicklink from cw_modules  where module_id = "'.$this->control_name.'"';
		$link_info        = $this->db->query("CALL sp_a_run ('SELECT','$link_query')");
		$link_result      = $link_info->result();
		$link_info->next_result();
		$this->quick_link = $link_result[0];
	}
	
	// PROVIDE TABLE VIEW
	public function get_table_head(){
		$table_query = 'select label_name,view_name,field_type,date_type from cw_form_setting  where prime_module_id = "'.$this->control_name.'" and input_view_type IN (1,2) and table_show = "1" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",user_right_for) ORDER BY table_sort asc';
		$table_info = $this->db->query("CALL sp_a_run ('SELECT','$table_query')");
		$result   = $table_info->result();
		$table_info->next_result();
		$this->table_head    = $result;
		$select_key          = array_column($result, "label_name");
		$this->select_query .= implode(",",$select_key);
	}
	//F and F Header Details
	// PROVIDE MONTHLY INPUT TABLE VIEW
	public function get_fandf_header_info(){
		$fanf_header_qry = 'select label_name,view_name,field_type from cw_form_setting  where prime_module_id = "employees" ORDER BY prime_form_id';
		$fanf_header_info = $this->db->query("CALL sp_a_run ('SELECT','$fanf_header_qry')");
		$fanf_header_result   = $fanf_header_info->result();
		$fanf_header_info->next_result();
		$this->fanf_header_info = $fanf_header_result;
	}
	// PROVIDE TABLE VIEW
	public function get_freeze_count(){
		$freeze_table_query = 'select left_freeze,right_freeze from cw_modules  where module_id = "'.$this->control_name.'" and trans_status = "1"';
		$freeze_table_info = $this->db->query("CALL sp_a_run ('SELECT','$freeze_table_query')");
		$freeze_result   = $freeze_table_info->result();
		$freeze_table_info->next_result();
		$this->freeze_list 	  = $freeze_result;
	}
	//PAssword Encrty
	public function get_password_encrypt(){
		$emp_data_qry = 'select employee_code,emp_name,date_of_birth,date_of_joining from cw_employees where trans_status = 1';
		$emp_data     = $this->db->query("CALL sp_a_run ('SELECT','$emp_data_qry')");
		$empresult = $emp_data->result_array();
		$emp_data->next_result();
		$this->emp_data_result = array_reduce($empresult, function ($result, $arr) {		
			    $result[$arr['employee_code']] = $arr;
			    return $result;
			}, array());
	}
	
	// PROVIDE MODLE VIEWS
	public function get_view_info(){
		$view_query = 'select * from cw_form_view_setting  where prime_view_module_id = "'.$this->control_name.'" and form_view_show = "1" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",view_user_right) ORDER BY form_view_sort asc';
		$view_data   = $this->db->query("CALL sp_a_run ('SELECT','$view_query')");
		$view_result = $view_data->result();
		$view_data->next_result();
		$this->view_info = $view_result;
	}
	
	// PROVIDE MODLE FORM INPUT VIEWS
	public function get_form_info(){
		if($this->control_name === 'monthly_input' || $this->control_name === 'fandf_monthly_input'){
			$control_name = 'employees';
		}else{
			$control_name = $this->control_name;
		}
		$from_query = 'select * from cw_form_setting  where prime_module_id = "'.$control_name.'" and field_show = "1" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",user_right_for) ORDER BY input_for,field_sort asc';
		$form_data   = $this->db->query("CALL sp_a_run ('SELECT','$from_query')");
		$form_result = $form_data->result();
		$form_data->next_result();
		$this->form_info = $form_result;
	}
	public function get_rowset_form_info(){
		$table_query = 'select label_name,view_name,field_type from cw_form_setting  where prime_module_id = "'.$this->control_name.'" and input_view_type IN (3) and table_show = "1" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",user_right_for) ORDER BY table_sort asc';
		$table_info = $this->db->query("CALL sp_a_run ('SELECT','$table_query')");
		$result   = $table_info->result_array();
		$table_info->next_result();
		$result = array_map(function($v){
		    return [$v['label_name'] => $v];
		}, $result);
		$result = call_user_func_array('array_merge', $result);
		$this->rowset_form_info    = $result;		
		return $result;
	}
	
	// PROVIDE MODLE TABLE ROLE BASED SEARCH
	public function get_role_condition(){
		$table_search_query = 'select where_condition from cw_form_table_search  where query_module_id = "'.$this->control_name.'" and query_for = "'.$this->logged_user_role.'" and trans_status = "1"';
		$table_search_data   = $this->db->query("CALL sp_a_run ('SELECT','$table_search_query')");
		$table_search_result = $table_search_data->result();
		$table_search_data->next_result();
		if($table_search_result){
			$where_condition  = str_replace('^','"',$table_search_result[0]->where_condition);
			$session_query  = 'select session_value from cw_session_value  where session_for = 1 and trans_status = "1"';
			$session_data   = $this->db->query("CALL sp_a_run ('SELECT','$session_query')");
			$session_result = $session_data->result();
			$session_data->next_result();
			foreach($session_result as $rslt){
				$session_value 	   = $rslt->session_value;
				if($session_value !== "access_data"){
					$saved_session_val = $this->session->userdata($session_value);
					$exist_val = "@".$session_value."@";
					$where_condition  = str_replace($exist_val,$saved_session_val,$where_condition);
					}
			}
			$where_condition  = str_replace(',','","',$where_condition);
			$this->role_condition = $where_condition;
		}
	}
	// PROVIDE ROLE BASED PICK LIST /*UDY-13-02-2020*/
	public function get_role_based_picklist($query_list_id,$module_id){		
		$logged_user_role = str_replace(',', '|', $this->logged_user_role);
		$pick_query = 'select pick_where_condition from cw_pick_base_search  where pick_module_id = "'.$module_id.'" and query_list_id = "'.$query_list_id.'" and pick_query_for REGEXP "(^|,)('.$logged_user_role.')(,|$)" and trans_status = "1"';
		$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
		$pick_result = $pick_data->result();
		$pick_data->next_result();
		$where_condition = "";
		if($pick_result){
			$where_condition  = str_replace('^','"',$pick_result[0]->pick_where_condition);
			$session_query  = 'select session_value from cw_session_value  where session_for = 1 and trans_status = "1"';
			$session_data   = $this->db->query("CALL sp_a_run ('SELECT','$session_query')");
			$session_result = $session_data->result();
			$session_data->next_result();
			foreach($session_result as $rslt){
				$session_value 	   = $rslt->session_value;
				if($session_value !== "access_data"){
					$saved_session_val = $this->session->userdata($session_value);
					$exist_val = "@".$session_value."@";
					$where_condition  = str_replace($exist_val,$saved_session_val,$where_condition);
				}
			}
		}
		$where_condition  = str_replace(',','","',$where_condition);
		return $where_condition;
	}
	// Get Default Financial Year
	public function get_financial_year(){
		$fin_query = 'SELECT prime_financial_setting_id,start_date,end_date from cw_financial_setting where set_as_default_financial_year = 1 and trans_status = "1"';
		$fin_data   = $this->db->query("CALL sp_a_run ('SELECT','$fin_query')");
		$fin_result = $fin_data->result();
		$fin_data->next_result();
		$this->financial_info = $fin_result;
		return $fin_result;
	}
	//PROVIDE SEARCH AND VIEW SELECT QUERY, DROPDOWN VALUES AND SEARCH FLITERS
	public function get_query_and_drop(){
		$this->view_select  = "$this->prime_table.$this->prime_id,";
		foreach($this->form_info as $setting){
			$prime_form_id      = (int)$setting->prime_form_id;
			$prime_module_id    = $setting->prime_module_id;
			$input_view_type    = (int)$setting->input_view_type;
			$input_for          = (int)$setting->input_for;
			$field_type         = (int)$setting->field_type;
			$label_id           = $setting->label_name;
			$label_name         = ucwords($setting->view_name);
			$field_length       = $setting->field_length;
			$field_decimals     = $setting->field_decimals;
			$pick_list_type     = (int)$setting->pick_list_type;
			$pick_list          = $setting->pick_list;
			$pick_table         = $setting->pick_table;
			$auto_prime_id      = $setting->auto_prime_id;
			$auto_dispaly_value = $setting->auto_dispaly_value;
			$field_isdefault    = (int)$setting->field_isdefault;
			$file_type          = (int)$setting->file_type;
			$mandatory_field    = (int)$setting->mandatory_field;
			$unique_field       = (int)$setting->unique_field;
			$search_show        = (int)$setting->search_show;
			$default_value      = (int)$setting->default_value;
			$pick_display       = $setting->pick_display_value;
			if($default_value === 0){
				$default_value = "";
			}
			$pick_drop   = array();
			$pick_master = array();
			$pick_key    = array();
			$pick_val    = array();
			$final_pick  = array();
			if($field_isdefault === 1){				
				if(($field_type === 5) || ($field_type === 7)){
					$where_condition = $this->get_role_based_picklist($prime_form_id,$prime_module_id);
					if($pick_list_type === 1){
						$pick_list_val   = explode(",",$pick_list);
						$pick_list_val_1 = $pick_list_val[0];
						$pick_list_val_2 = $pick_list_val[1];
						if($pick_display){
							$pick_list = "$pick_list_val_1,CONCAT_WS(\" - \", $pick_display) as $pick_list_val_2";
						}
						if($label_name === 'loan_type' && $prime_module_id === 'loan'){
							$where_condition = ' and loan_check = 1';
						}
						if($pick_table === "cw_category"){ //and prime_category_id != 1
							$pick_query = "select $pick_list from $pick_table where trans_status = 1 $where_condition";
						}else
						if($pick_table === "cw_print_info" && $label_id === "design_template" || $label_id === "template"){
							$pick_query = "select $pick_list from $pick_table where trans_status = 1 and print_info_module_id = \"$this->control_name\" $where_condition";
						}else{
							$pick_query = "select $pick_list from $pick_table where trans_status = 1 $where_condition";
						}
						$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
						$pick_result = $pick_data->result();
						$pick_data->next_result();
						if($pick_result){
							$pick_key   = array_column($pick_result, $pick_list_val_1);
							$pick_val   = array_column($pick_result, $pick_list_val_2);
							$final_pick = array_combine( $pick_key, $pick_val);
						}
						$final_pick = array("" => "---- $label_name ----") + $final_pick;
						$this->master_pick[$label_id]   = $final_pick;
						 //array_unshift($final_pick,"---- $label_name ----");
						$this->all_pick[$prime_form_id] = $final_pick;
	  					//THIS IS GET A EMPLOYEE ALL PICKLISTS
						$get_components = 'select prime_form_id,prime_module_id,label_name,view_name from `cw_form_setting` where prime_module_id = "employees" and field_type = 5 ORDER BY label_name';
						$get_components_info   = $this->db->query("CALL sp_a_run ('SELECT','$get_components')");
						$get_components_result = $get_components_info->result();
						$get_components_info->next_result();
						$components[""]        = "---- Select Component ----";
						foreach($get_components_result as $component){
							$prime_form_id     = $component->prime_form_id;
							$components_name   = strtoupper($component->view_name);
							$this->components[$this->xss_clean($prime_form_id)] = $this->xss_clean($components_name);	
							// $this->emp_label_arr[$this->xss_clean($prime_form_id)] = $this->xss_clean($component->label_name);	
						}
					}else
					if($pick_list_type === 2){
						$pick_list_val_1 = $pick_table."_id";
						$pick_list_val_2 = $pick_table."_value";
						$pick_list_val_3 = $pick_table."_status";
						
						$pick_query = "select $pick_list_val_1,$pick_list_val_2 from $pick_table where $pick_list_val_3 = 1 $where_condition";
						$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
						$pick_result = $pick_data->result();
						$pick_data->next_result();
						if($pick_result){
							$pick_key   = array_column($pick_result, $pick_list_val_1);
							$pick_val   = array_column($pick_result, $pick_list_val_2);				
							$final_pick = array_combine( $pick_key, $pick_val);
						}
						$final_pick = array("" => "---- $label_name ----") + $final_pick;
						$this->master_pick[$label_id]   = $final_pick;
						//array_unshift($final_pick,"---- $label_name ----");
						$this->all_pick[$prime_form_id] = $final_pick;
					}
				}else
				if($field_type === 9){
					$pick_query = "select $auto_prime_id,$auto_dispaly_value from $pick_table where trans_status = 1";
					$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
					$pick_result = $pick_data->result();
					$pick_data->next_result();
					if($pick_result){
						$pick_key   = array_column($pick_result, $auto_prime_id);
						$pick_val   = array_column($pick_result, $auto_dispaly_value);
						$final_pick = array_combine( $pick_key, $pick_val);
					}
					$this->master_pick[$label_id]   = $final_pick;
				}
				if(($input_view_type === 1) || ($input_view_type === 2)){
					$this->view_select  .= "$this->prime_table.$label_id,";
					if($search_show === 1){						
						$this->fliter_list[] = array('label_id'=> $label_id, 'label_name'=> $label_name, 'field_isdefault'=> $field_isdefault, 'array_list'=> $final_pick, 'field_type'=> $field_type);
					}
				}
			}
		}
		$this->view_select   = rtrim($this->view_select,',');
		// ONLY FOR EMPLOYEE
		if($this->control_name === "employees"){
			$this->view_select   = $this->view_select .',user_name,password';
		}		
	}
	// PROVIDE MODLE ONLOAD CONDITION & FORMULA
	public function get_condition(){
		$condition_query = 'select * from cw_form_condition_formula  where cond_module_id = "'.$this->control_name.'" and trans_status = "1" and FIND_IN_SET("'.$this->logged_role.'",condition_for)';
		$condition_data   = $this->db->query("CALL sp_a_run ('SELECT','$condition_query')");
		$condition_result = $condition_data->result();		
		$condition_data->next_result();
		$load_script = "";
		foreach($condition_result as $condition){			
			$prime_cond_id         = $condition->prime_cond_id;
			$cond_module_id        = $condition->cond_module_id;
			$condition_label_name  = strtolower(str_replace(" ","_",$condition->condition_label_name));
			$condition_type        = (int)$condition->condition_type;
			$condition_check_form  = explode(",",$condition->condition_check_form);
			$condition_bind_to     = explode(",",$condition->condition_bind_to);
			$on_bind_input   = "";
			$on_change_input = "";
			$on_blur_input   = "";
			
			foreach($condition_check_form as $label_name){				
				$cond_from_query = 'select field_type,label_name from cw_form_setting  where prime_module_id = "'.$this->control_name.'" and label_name in ("'.$label_name.'") ORDER BY input_for,field_sort asc';
				$cond_form_data   = $this->db->query("CALL sp_a_run ('SELECT','$cond_from_query')");
				$cond_form_result = $cond_form_data->result();
				$cond_form_data->next_result();
				$field_type = (int)$cond_form_result[0]->field_type;
				/*============ 
					NOTE:  AUTO COMPLETE BOX & FILE UPLOAD BOX ARE NOT INCLUDED IN ON LOAD SCRIPT
				============*/
				if(($field_type === 1) || ($field_type === 2) || ($field_type === 3) || ($field_type === 11) || ($field_type === 12)){
					$on_bind_input  .= "$label_name,";
				}else
				if(($field_type === 5) || ($field_type === 6) || ($field_type === 7)){
					$on_change_input  .= "$label_name,";
				}
				if($condition_type === 2){
					if(($field_type === 4) || ($field_type === 13)){
						$on_blur_input  .= "$label_name,";
					}
				}
			}
			$check_input = "";
			if($on_bind_input){
				$on_bind_input = rtrim($on_bind_input,',');
				$on_bind_input = str_replace(",",",#",$on_bind_input);
				$on_bind_input = "#".$on_bind_input;
				$check_input .= "$on_bind_input";
			}			
			
			if($on_change_input){
				$on_change_input = rtrim($on_change_input,',');
				$on_change_input = str_replace(",",",#",$on_change_input);
				$on_change_input = "#".$on_change_input;
				if($check_input){
					$check_input .= ",$on_change_input";
				}else{
					$check_input .= "$on_change_input";
				}
				
			}
			
			if($on_blur_input){
				$on_blur_input = rtrim($on_blur_input,',');
				$on_blur_input = str_replace(",",",#",$on_blur_input);
				$on_blur_input = "#".$on_blur_input;
				if($check_input){
					$check_input .= ",$on_blur_input";
				}else{
					$check_input .= "$on_blur_input";
				}
			}
			
			$send_for  = implode(",",$condition_check_form);
			$send_data = "prime_cond_id:$prime_cond_id,for_input:'$send_for',";
			foreach($condition_check_form as $check_form){
				$send_data .= "$check_form:$('#$check_form').val(),";
			}
			$send_data = "{".rtrim($send_data,',')."}";
			
			//BIND VALUE FROM DATABASE TABLE
			if($condition_type === 1){
				if($on_bind_input){
					$fill_input = "";
					foreach($condition_bind_to as $bind_to){
						$fill_val    = "ui.item.".$bind_to;
						$fill_input .= "$('#$bind_to').val($fill_val);\n";
					}
					$send_url     = site_url("$this->control_name/bind_autocomplete_suggest");
					$load_script .= "$('$on_bind_input').autocomplete({
										 source: function(request, response) {
											$.getJSON('$send_url',{term:request.term, prime_cond_id:$prime_cond_id },response);
										},
										minChars:2,
										autoFocus: true,
										delay:10,
										appendTo: '.modal-content',
										select: function(e, ui) {
											$fill_input
											return false;
										}
									});\n";
				}
				if($on_change_input){
					$fill_input = "";
					foreach($condition_bind_to as $bind_to){
						$fill_val    = "rslt[0].".$bind_to;
						$fill_input .= "$('#$bind_to').val($fill_val);\n";
					}
					
					$send_url  = site_url("$this->control_name/bind_change_suggest");
					$load_script .= "$('$on_change_input').change(function(){
										var isValid = true;
										$('$on_change_input').each(function() {
										  if ($(this).val() === '') {
											isValid = false;
											$(this).addClass('error');
										  }else{
											 $(this).removeClass('error');
										  }
										});
										if(isValid){
											$.ajax({
												type: 'POST',
												url: '$send_url',
												data:$send_data,
												success: function(data) {
													var rslt = JSON.parse(data);
													$fill_input
												}
											});
										}
									});\n";
				}
			}else
			if($condition_type === 2){
				$fill_input = "";
				foreach($condition_bind_to as $bind_to){
					$fill_val    = "rslt.".$bind_to;
					/*if($this->control_name === 'employees'){
						$fill_input .= "$('#$bind_to').val($fill_val);";
					}else{*/
						$fill_input .= "$('#$bind_to').val($fill_val);\n $('#$bind_to').trigger('change');";
					//}
				}
				$send_url  = site_url("$this->control_name/calculation_suggest");
				$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){
										$.ajax({
											type: 'POST',
											url: '$send_url',
											data:$send_data,
											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(){
		$search_term      = $this->input->post_get('term');		
		$prime_form_id    = $this->input->get('prime_form_id');
		$depen_pick_list  = $this->input->get('depen_pick_list');
		$depend_hidden_id = $this->input->get('depend_hidden_id');
		$label_id_val 	  = $this->input->get('label_id');
		$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]){
			$pick_table          = $form_result[$prime_form_id]['pick_table'];
			$pick_list           = $form_result[$prime_form_id]['pick_list'];
			$auto_prime_id       = $form_result[$prime_form_id]['auto_prime_id'];
			$auto_dispaly_value  = $form_result[$prime_form_id]['auto_dispaly_value'];
			$pick_display_value  = $form_result[$prime_form_id]['pick_display_value'];
			$depand_join 	= "";
			$depand_where   = "";
			if((int)$depen_pick_list === 1){
				$pick_table_sec = $form_result[$depend_hidden_id]['pick_table'];
				$depand_tbl1 	= $form_result[$prime_form_id]['table_column1'];
				$depand_tbl2 	= $form_result[$prime_form_id]['table_column2'];
				$field_type 	= $form_result[$depend_hidden_id]['field_type'];
				$depen_pick_type 	= $form_result[$depend_hidden_id]['pick_list_type'];
				$depen_pick_list 	= $form_result[$depend_hidden_id]['pick_list'];
				if((int)$field_type === 5){
					$pick_list_val   = explode(",",$depen_pick_list);
					if((int)$depen_pick_type === 1){
						$depand_display = $pick_list_val[0];
					}else
					if((int)$depen_pick_type === 2){
						$depand_display = $pick_table."_id";
					}
				}else
				if((int)$field_type === 9){
					$depand_display = $form_result[$depend_hidden_id]['auto_prime_id'];
				}
				// $depand_display = $form_result[$depend_hidden_id]['auto_prime_id'];
				$pick_table 	= $this->input->get('pick_table');
				$table_column2 	= $this->input->get('table_column2');
				$pick_tbl_val 	= $this->input->get('pick_tbl_val');
				$depen_select 	= $this->input->get('depen_select');
				$depand_join 	= " inner join $pick_table_sec on $pick_table_sec.$depand_tbl1 = $pick_table.$depand_tbl2";
				$depand_where 	= " and $pick_table_sec.trans_status = 1 and $pick_table_sec.$depand_display = \"$depen_select\"";
			}
			$where_condition 	   = $this->get_role_based_picklist($prime_form_id,$form_result[$prime_form_id]['prime_module_id']);
			$pick_list 			 = explode(",", $pick_list);
			$pick_list 			 = "$pick_table.".implode(",$pick_table.", $pick_list);
			$pick_display_value  = explode(",", $pick_display_value);
			$pick_display_value  = "$pick_table.".implode(",$pick_table.", $pick_display_value);
			$auto_list 	   = "CONCAT(".str_replace(",",'," - ",',$pick_list).") as auto_list";
			$display_list  = "CONCAT(".str_replace(",",'," - ",',$pick_display_value).") as display_list";
			if($auto_prime_id){
				$auto_prime_ids = "$pick_table.$auto_prime_id,";
			}
			if($auto_dispaly_value){
				$auto_dispaly_values = "$pick_table.$auto_dispaly_value,";
			}
			$suggest_query = "select $auto_prime_ids $auto_dispaly_values $auto_list,$display_list from $pick_table $depand_join where $pick_table.trans_status = 1 $depand_where";
			$col_list      = explode(",",$pick_list);
			$suggest_query .= " and ";
			$where_query  = "";
			foreach($col_list as $col){
				$search_term = str_replace('"',"~",$search_term);
				$search_term = str_replace("'","`",$search_term);
				$search_term = str_replace("&","^",$search_term);
				$where_query .= $col.' like "%'.$search_term.'%" or ';
			}
			$where_query    = rtrim($where_query," or ");
			$suggest_query .= '('.$where_query.')';
			$suggest_query .= $where_condition;
			$suggest_query .= ' limit 0,50';
			$suggest_data   = $this->db->query("CALL sp_a_run ('SELECT','$suggest_query')");
			$suggest_result = $suggest_data->result();
			$suggest_data->next_result();
			foreach($suggest_result as $result){
				$suggest_prime_id  = $result->$auto_prime_id;
				$suggest_dispaly   = $result->$auto_dispaly_value;
				$suggest_list      = $result->auto_list;
				$suggest_list = str_replace("~",'"',$suggest_list);
				$suggest_list = str_replace("`","'",$suggest_list);
				$suggest_list = str_replace("^","&",$suggest_list);
				$suggest_dispaly_list = $result->display_list;
				$suggest_dispaly_list = str_replace("~",'"',$suggest_dispaly_list);
				$suggest_dispaly_list = str_replace("`","'",$suggest_dispaly_list);
				$suggest_dispaly_list = str_replace("^","&",$suggest_dispaly_list);
				$suggestions[] = array('value' => $suggest_prime_id, 'label' => $suggest_list, 'display_name' => $suggest_dispaly_list);
			}
		}
		if(empty($suggestions)){
			$suggestions[] = array('value' => "0", 'label' => "No data found for this search");
		}
		echo json_encode($suggestions);		
	}
	
	//PROVIDE AUTOCOMPLETE DROP DOWN TO FILL MULTI INPUT BOX
	public function bind_autocomplete_suggest(){
		$search_term      = $this->input->post_get('term');
		$prime_cond_id    = $this->input->post_get('prime_cond_id');
		echo $this->get_bind_final_query("autocomplete",$search_term,$prime_cond_id);
	}
	
	//PROVIDE DATA WHILE ON CHANGE EVENT TO FILL MULTI INPUT BOX
	public function bind_change_suggest(){
		$for_input        = $this->input->post_get('for_input');
		$prime_cond_id    = $this->input->post_get('prime_cond_id');
		$search_term      = $this->input->post_get($for_input);
		echo $this->get_bind_final_query("change",$search_term,$prime_cond_id);		
	}
	// UDY NEED TO REVIEW
	//PROVIDE QUERY AND RESULT ARRAY TO BIND INPUT
	public function get_bind_final_query($from,$search_term,$prime_cond_id){
		/*============ 
			NOTE:  VAR FROM NOT USED MAY CAN USE IN FURTURE PROCESS
		============*/
		$cond_query = 'select * from cw_form_condition_formula  where prime_cond_id = "'.$prime_cond_id.'" and trans_status = 1';
		$cond_data   = $this->db->query("CALL sp_a_run ('SELECT','$cond_query')");
		$cond_result = $cond_data->result();
		$cond_data->next_result();
		$final_qry = "";
		if($cond_result){
			$cond_module_id       = $cond_result[0]->cond_module_id;
			$condition_check_form = $cond_result[0]->condition_check_form;
			$condition_bind_to    = $cond_result[0]->condition_bind_to;
			$condition_table      = $cond_result[0]->condition_table;
			
			$table_query = 'select * from cw_form_table_cond_for  where table_cond_id = "'.$prime_cond_id.'" ORDER BY abs(line_sort) asc';
			$table_data   = $this->db->query("CALL sp_a_run ('SELECT','$table_query')");
			$table_result = $table_data->result();
			$table_data->next_result();
			$line_table_query = "";
			foreach($table_result as $table){
				$line_prime_table = $table->line_prime_table;
				$line_prime_col   = $table->line_prime_col;
				$line_join_type   = $table->line_join_type;
				$line_join_table  = $table->line_join_table;
				$line_join_col    = $table->line_join_col;
				$line_sort        = $table->line_sort;
				
				$module_name      = str_replace("cw_","",$line_prime_table);
				$prime_id         = "prime_".$module_name."_id";
				
				$join_module_name      = str_replace("cw_","",$line_join_table);
				$join_prime_id         = "prime_".$join_module_name."_id";
				if((int)$line_sort === 1){
					$line_table_query .= " $line_prime_table $line_join_type join $line_join_table on $line_join_col = $line_prime_col "; 
				}else{
					$line_table_query .= " $line_join_type join $line_join_table on $line_join_col = $line_prime_col"; 
				}
			}
			if(!$line_table_query){
				$module_name      = str_replace("cw_","",$condition_table);
				$prime_id         = "prime_".$module_name."_id";
				$line_table_query = " $condition_table ";
			}
			
			
			$for_input_query = 'select * from cw_form_for_input  where input_for_cond_id = "'.$prime_cond_id.'" and trans_status = 1';
			$for_input_data   = $this->db->query("CALL sp_a_run ('SELECT','$for_input_query')");
			$for_input_result = $for_input_data->result();
			$for_input_data->next_result();
			$for_line_input_query = "";
			foreach($for_input_result as $for_input){
				$line_input_for       = $for_input->line_input_for;
				$line_input_for_table = $for_input->line_input_for_table;
				$line_input_for_col   = $for_input->line_input_for_col;	
								
				$for_line_input_query .= $line_input_for_col.' like "'.$search_term.'%" or ';
			}
			if($for_line_input_query){
				$for_line_input_query  = " where ". rtrim($for_line_input_query," or ");
			}
			
			$input_query = 'select * from cw_form_bind_input  where input_cond_id = "'.$prime_cond_id.'" and trans_status = 1';
			$input_data   = $this->db->query("CALL sp_a_run ('SELECT','$input_query')");
			$input_result = $input_data->result();
			$input_data->next_result();
			$line_input_query = "";
			foreach($input_result as $input){
				$line_input_bind_to    = $input->line_input_bind_to;
				$line_input_bind_table = $input->line_input_bind_table;
				$line_input_bind_col   = $input->line_input_bind_col;
				
				$select_query  = 'select field_type from cw_form_setting  where prime_module_id = "'.$cond_module_id.'" and label_name = "'.$line_input_bind_to.'"';
				$select_data   = $this->db->query("CALL sp_a_run ('SELECT','$select_query')");
				$select_result = $select_data->result();
				$select_data->next_result();
				$field_type = (int)$select_result[0]->field_type;
				if(($field_type === 4) || ($field_type === 13)){
					$line_input_query .= 'DATE_FORMAT('.$line_input_bind_col.',"%d-%m-%Y") as '.$line_input_bind_to.',';
				}else{
					$line_input_query .= "$line_input_bind_col as $line_input_bind_to,";
				}
			}
			if($line_input_query){
				$line_input_query  = rtrim($line_input_query,',');
			}else{
				$line_input_query  = " * ";
			}
			$final_qry = "select $line_input_query from $line_table_query $for_line_input_query";
		}
		if($final_qry){
			$final_data   = $this->db->query("CALL sp_a_run ('SELECT','$final_qry')");
			$final_result = $final_data->result();
			$final_data->next_result();
			foreach($final_result as $rslt){
				$line = array();
				$lable = "";
				foreach($input_result as $input){
					$line_input_bind_to    = $input->line_input_bind_to;
					$rslt_val = $rslt->$line_input_bind_to;
					$line[$line_input_bind_to] =  $rslt_val;
					if($rslt_val){
						$lable .= "$rslt_val - ";
						}
				}
				$lable  = rtrim($lable," - ");
				$line['value'] = '';
				$line['label'] = $lable;
				$suggestions[] = $line;
			}
		}
		if(empty($suggestions)){
			$suggestions[] = array('value' => "0", 'label' => "No data found for this search");
		}
		return json_encode($suggestions);
	}
	
	//PROVIDE DATA FOR  ONCHANGE CALCUATION
	public function calculation_suggest(){
		$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();	
		// echo "<pre>::cond_query => $cond_query";
		// 	print_r($cond_result);die;
		$condition_check_form    = explode(",",$cond_result[0]->condition_check_form);
		$condition_bind_to       = $cond_result[0]->condition_bind_to;
		$condition_table         = $cond_result[0]->condition_table;
		$condition_type          = $cond_result[0]->condition_type;
		$is_drop_down            = (int)$cond_result[0]->is_drop_down;
		$cond_drop_down          = $cond_result[0]->cond_drop_down;
		$fianl_result_array      = array();
		if($is_drop_down === 1){
			$search_term         = $this->input->post_get($cond_drop_down);
			$input_query         = 'select * from cw_form_bind_input  where input_cond_id = "'.$prime_cond_id.'" and line_input_bind_table = "'.$search_term.'"';
			$input_data          = $this->db->query("CALL sp_a_run ('SELECT','$input_query')");
			$input_result        = $input_data->result();
			$input_data->next_result();

			$line_input_bind_col = "";
			foreach($input_result as $input){
				$line_input_bind_to   = $input->line_input_bind_to;
				$line_input_bind_col  = $input->line_input_bind_col;
				$line_input_bind_col  = str_replace("~","'",$line_input_bind_col);
				$line_input_bind_col  = str_replace("!",'"',$line_input_bind_col);
				if($line_input_bind_col){
					foreach($condition_check_form as $check_form){
						if(strpos($line_input_bind_col,"@$check_form@") !== false) {
								$value = $this->input->post_get($check_form);
								if(strpos($check_form,"date") !== false) {
									$value = new DateTime($value);
									$value = $value->format("Y-m-d");
									$value = "'$value'";
								}
							$line_input_bind_col = str_replace("@$check_form@",$value, $line_input_bind_col);
						}
					}
					$dynamic_file_name= "calculation_file/".$line_input_bind_to."_".$this->logged_id.".php";
					unlink("$dynamic_file_name");
					$fname = $line_input_bind_to."(){";
					$code = "<?php function $fname $line_input_bind_col }?>";
					// echo "<pre>::code => $fname";
					// echo "<pre>:: => $line_input_bind_col";die;
					
					// echo "dynamic_file_name:: $dynamic_file_name";die;
					fopen("$dynamic_file_name", "w");
					file_put_contents("$dynamic_file_name",$code);
					chmod($dynamic_file_name, 0777);
					require_once("$dynamic_file_name");
					$fianl_result_array[$line_input_bind_to] =  $line_input_bind_to();
					unlink("$dynamic_file_name");
				}
			}
		}else{
			$input_query = 'select * from cw_form_bind_input  where input_cond_id = "'.$prime_cond_id.'"';
			$input_data   = $this->db->query("CALL sp_a_run ('SELECT','$input_query')");
			$input_result = $input_data->result();
			$input_data->next_result();
			$line_input_bind_col = "";
			foreach($input_result as $input){
				$line_input_bind_to    = $input->line_input_bind_to;
				$line_input_bind_col   = $input->line_input_bind_col;
				$line_input_bind_col  = str_replace("~","'",$line_input_bind_col);
				$line_input_bind_col  = str_replace("!",'"',$line_input_bind_col);
				if($line_input_bind_col){
					foreach($condition_check_form as $check_form){
						if(strpos($line_input_bind_col,"@$check_form@") !== false) {
								$value = $this->input->post_get($check_form);
								if(strpos($check_form,"date") !== false) {
									$value = new DateTime($value);
									$value = $value->format("Y-m-d");
									$value = "'$value'";
								}
							$line_input_bind_col = str_replace("@$check_form@",$value, $line_input_bind_col);
						}
					}				
					$dynamic_file_name= "calculation_file/".$line_input_bind_to."_".$this->logged_id.".php";
					unlink("$dynamic_file_name");
					$fname = $line_input_bind_to."(){";
					$code = "<?php function $fname $line_input_bind_col }?>";
					fopen("$dynamic_file_name", "w");
					file_put_contents("$dynamic_file_name",$code);
					chmod($dynamic_file_name, 0777);
					require_once("$dynamic_file_name");
					$fianl_result_array[$line_input_bind_to] =  $line_input_bind_to();
					unlink("$dynamic_file_name");
				}
			}
		}			
		echo json_encode($fianl_result_array);
	}
	
	// UDY NEED TO REVIEW
	/* ==============================================================*/
	/* ================= CONDITION OPERATION - END ==================*/
	/* ==============================================================*/
	
	/* ==============================================================*/
	/* ================== ROWSET OPERATION - START ==================*/
	/* ==============================================================*/
	// ROWSET SAVE
	public function rowset_save(){
		$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        = (int)$this->input->post('prime_id');
		
		$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(){
		$row_id          = (int)$this->input->post('row_id');
		$view_id         = (int)$this->input->post('view_id');
		$table_name      = $this->input->post('table_name');
		$table_prime_id  =	 "prime_".$table_name."_id";
		$table_name      = $this->db->dbprefix($table_name);

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

		$final_qry  = "select * from $table_name " .' where '.$table_prime_id.' = "'.$row_id.'" and  trans_status = "1"';
		$row_data   = $this->db->query("CALL sp_a_run ('SELECT','$final_qry')");
		$row_result = $row_data->result();
		$row_data->next_result();
		
		$form_qry    = 'select * from cw_form_setting where prime_module_id = "'.$controller_name.'" and  input_for = "'.$view_id.'" and  input_view_type = "3" and trans_status = "1"';
		$form_data   = $this->db->query("CALL sp_a_run ('SELECT','$form_qry')");
		$form_result = $form_data->result();
		$form_data->next_result();
		$rslt_info = array();
		$rslt_info[$table_prime_id] = array('input_value'=>$row_result[0]->$table_prime_id,'field_type'=>1); ;
		foreach($form_result as $form){
			$prime_form_id      = (int)$form->prime_form_id;
			$label_name         = $form->label_name;
			$field_type         = $form->field_type;
			$pick_table         = $form->pick_table;
			$auto_prime_id      = $form->auto_prime_id;
			$auto_dispaly_value = $form->auto_dispaly_value;
			$mandatory_field    = (int)$form->mandatory_field;			
			$input_value        = $row_result[0]->$label_name;
			$date_type      	= $form->date_type;
			if((int)$field_type === 4){
				if((int)$date_type === 1){
					if($input_value === '0000-00-00' || $input_value ==='01-01-1970' || $input_value === 'NULL'){
						$input_value = "";
					}else{
						$input_value = date('d-m-Y',strtotime($input_value));
					}
				}else{
					$input_value = $input_value;
				}
				if($input_value === "01-01-1970" || $input_value === 'NULL' || $input_value === "0000-00-00"){
					$input_value = "";
				}
				$rslt_info[$label_name] = array('input_value'=>$input_value,'field_type'=>$field_type,'mandatory_field'=>$mandatory_field);
			}else
			if((int)$field_type === 13){
				$input_date =  date('d-m-Y',strtotime($input_value));
				if($input_date === "01-01-1970" || $input_date === 'NULL' || $input_date === '' || $input_date === "00-00-0000" || $input_date === '30-11--0001'){
					$input_value = "";
				}else{
					$input_value = $input_value;
				}
				$rslt_info[$label_name] = array('input_value'=>$input_value,'field_type'=>$field_type,'mandatory_field'=>$mandatory_field);
			}else
			if((int)$field_type === 8){
				$input_value = str_replace("~",'"',$input_value);
				$input_value = str_replace("`","'",$input_value);
				$input_value = str_replace("^","&",$input_value);
				$rslt_info[$label_name] = array('input_value'=>$input_value,'field_type'=>$field_type,'mandatory_field'=>$mandatory_field);
			}else
			if((int)$field_type === 9){
				$rslt_info[$label_name] = array('input_value'=>$input_value,'field_type'=>$field_type,'mandatory_field'=>$mandatory_field);
				$pick_query = 'select '.$auto_dispaly_value.' from '.$pick_table.' where '.$auto_prime_id.' = "'.$input_value.'" and trans_status = 1';
				$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
				$pick_result = $pick_data->result();
				$pick_data->next_result();
				$input_value = $pick_result[0]->$auto_dispaly_value;
				$label_name  = $label_name."_hidden_".$prime_form_id;
				$rslt_info[$label_name] = array('input_value'=>$input_value,'field_type'=>$field_type,'mandatory_field'=>$mandatory_field);
			}else
			if((int)$field_type === 10){
				$old_label_name 	        = "old_".$label_name;
				$rslt_info[$label_name]     = array('input_value'=>$input_value,'field_type'=>$field_type,'mandatory_field'=>$mandatory_field);
				$rslt_info[$old_label_name] = array('input_value'=>$input_value,'field_type'=>$field_type,'mandatory_field'=>$mandatory_field);
			}else{
				$rslt_info[$label_name] = array('input_value'=>$input_value,'field_type'=>$field_type,'mandatory_field'=>$mandatory_field);
			}
		}
		echo json_encode(array('success' => TRUE, 'row_result' => $rslt_info,'table_name'=> $table_name));
	}
	
	//ROW SET REMOVE DATA
	public function row_set_remove(){
		$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){
		$controller_name  = $this->control_name;
		if($controller_name === "employee_self_portal"){
			$controller_name  = "employees";
		}
		$view_qry    = 'select * from cw_form_view_setting where prime_form_view_id = "'.$view_id.'" and prime_view_module_id = "'.$controller_name.'" and  form_view_type = "3" and trans_status = 1';
		$view_data   = $this->db->query("CALL sp_a_run ('SELECT','$view_qry')");
		$view_result = $view_data->result();
		$view_data->next_result();
		$prime_form_view_id   = $view_result[0]->prime_form_view_id;
		$prime_view_module_id = $view_result[0]->prime_view_module_id;
		$form_view_label_name = $view_result[0]->form_view_label_name;
		
		$div_id       	 = $form_view_label_name."_div_".$prime_form_view_id;
		$table_id        = $form_view_label_name."_tbl_".$prime_form_view_id;
		$table_name      = $controller_name."_".$form_view_label_name;
		$row_prime_id    = "prime_".$table_name."_id";
		$table_name      =  $this->db->dbprefix($table_name);
		$table_prime_id  = "prime_".$controller_name."_id";
		
		$form_qry    = 'select prime_form_id,view_name,label_name,field_type,date_type,pick_list_type,pick_list,pick_table,auto_prime_id,auto_dispaly_value from cw_form_setting where prime_module_id = "'.$controller_name.'" and  input_for = "'.$prime_form_view_id.'" and  input_view_type = "3" and table_show = "1" and trans_status = "1" order by abs(field_sort)';
		$form_data   = $this->db->query("CALL sp_a_run ('SELECT','$form_qry')");
		$form_result = $form_data->result();
		$form_data->next_result();
		$table_head = array();
		$thead_line = "";
		$select_query = "$table_name.$row_prime_id,$table_name.$table_prime_id,";
		foreach($form_result as $form){
			$prime_form_id  = (int)$form->prime_form_id;
			$view_name      = $form->view_name;
			$label_name     = $form->label_name;
			$field_type     = (int)$form->field_type;
			$pick_list_type = (int)$form->pick_list_type;
			$pick_list      = $form->pick_list;
			$pick_table     = $form->pick_table;
			$auto_prime_id      = $form->auto_prime_id;
			$auto_dispaly_value = $form->auto_dispaly_value;
			$date_type 	 		= $form->date_type;
			if((int)$field_type === 4){
				if((int)$date_type === 1){
					$select_query .= 'DATE_FORMAT('.$table_name.'.'.$label_name.', "%d-%m-%Y") as '.$label_name.' , ';
				}else{
					$select_query .= "$table_name.$label_name , ";
				}
			}else
			if((int)$field_type === 13){
				$select_query .= 'DATE_FORMAT('.$table_name.'.'.$label_name.', "%d-%m-%Y H:i:s") as '.$label_name.' , ';
			}else
			if(($field_type === 5) || ($field_type === 7)){
				if($pick_list_type === 1){
					if($label_name === "component_value" && $this->control_name === "holiday_entry"){
						/* Custom code for Holiday Entry Module START */
						$component_query  = 'SELECT pick_table,pick_list,components FROM cw_general_setting inner join cw_form_setting on cw_form_setting.prime_form_id = cw_general_setting.components WHERE entry_parameter_type = 2 and cw_general_setting.trans_status = 1';
						$component_info   = $this->db->query("CALL sp_a_run ('SELECT','$component_query')");
						$component_result = $component_info->result();
						$component_info->next_result();			
						$pick_list   = $component_result[0]->pick_list;
						$pick_table = $component_result[0]->pick_table;
						$components = $component_result[0]->components;	
						$pick_list_val   = explode(",",$pick_list);
						$pick_list_val_1 = $pick_list_val[0];
						$pick_list_val_2 = $pick_list_val[1];
						/* Custom code for Holiday Entry Module END */
					}else{
						$pick_list_val   = explode(",",$pick_list);
						$pick_list_val_1 = $pick_list_val[0];
						$pick_list_val_2 = $pick_list_val[1];
					}
					$pick_query_as = $pick_table."_".$prime_form_id;
					$select_query .= "$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,' , ');
		if($table_name === "cw_holiday_entry_holiday_data"){
			$order_qry = 'order by cw_holiday_entry_holiday_data.holiday_date desc';
		}else{
			$order_qry = 'order by abs('.$table_name.'.'.$row_prime_id.') desc';
		}
		$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;
				$rowset_form_info = $this->get_rowset_form_info();
				$field_type       = $rowset_form_info[$label]['field_type'];
				$value            = $data->$label;
				if((int)$field_type === 4 || (int)$field_type === 13){
					if($value === "00-00-0000" || $value === 'NULL' || $value === "00-00-0000 00:00:00"){
						$td_line .= "<td></td>";
					}else{
						$td_line .= "<td>$value</td>";
					}
				}else
				if((int)$field_type === 8){//textbox only
					$value = str_replace("~",'"',$value);
					$value = str_replace("`","'",$value);
					$value = str_replace("^","&",$value);
					$td_line .= "<td>$value</td>";
				}else
				if((int)$field_type === 10){
					if($datas_exp === "" || $datas_exp === NULL){
						$td_line .= "<td>No Preview Available</td>";
					}else{
						$td_line .= "<td><a href='$datas_exp' format.pdf='' target='_blank' style='cursor: pointer;''><i class='fa fa-download' style='color:red;' aria-hidden='true'></i></a></td>";
					}
				}else{
					$td_line .= "<td>$value</td>";
				}
			}
			$row_id   = $data->$row_prime_id;
			$tab_name = $controller_name."_".$form_view_label_name;
			$illustration_btn = "";
			if($form_view_label_name === "eligibility_information"){
				$illustration_btn   = "<a class='btn btn-edit btn-xs row_btn' onclick = add_illustration('$row_id','$tab_name','$prime_form_view_id');>Illustration</a>";
			}
			$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>";
		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(){
		$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){
		$filename = dirname(__FILE__)."/php_excel/PHPExcel/IOFactory.php";
		include($filename);
		if($import_id < 0){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}
		$excel_path_qry    = 'select * from cw_import where import_id = "'.$import_id.'"';
		$excel_path_info   = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
		$excel_path_result = $excel_path_info->result();
		$excel_path_info->next_result();
		if(!$excel_path_result){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}else{
			$excel_file_path    = $excel_path_result[0]->excel_file_path;
			$module_id          = $excel_path_result[0]->module_id;
			$excel_format       = $excel_path_result[0]->excel_format;
			$excel_sheet_name   = (int)$excel_path_result[0]->excel_sheet_name;
			$excel_row_start    = (int)$excel_path_result[0]->excel_start_row;
			$excel_row_end      = (int)$excel_path_result[0]->excel_end_row;
			$format_qry 	    = 'select * from cw_util_excel_format where prime_excel_format_id = "'.$excel_format.'" and cw_util_excel_format.trans_status = 1';
			$format_info    = $this->db->query("CALL sp_a_run ('SELECT','$format_qry')");
			$format_rslt    = $format_info->result();
			$format_info->next_result();
			if(!$format_rslt){
				return json_encode(array('success' => false, 'message' => "Please add excel format before import"));
			}else{
				$exist_column_name = explode(",",$format_rslt[0]->exist_column_name);
				$excel_format_qry 	= 'select IFNULL(pick_list_import,0) as pick_list_import,view_name,duplicate_data,picklist_data,field_type,pick_table,pick_list_type,pick_list,mandatory_field,field_isdefault,excel_line_column_name,excel_line_value from cw_util_excel_format_line inner join cw_form_setting on label_name = excel_line_column_name where excel_line_module_id = "'.$module_id.'" and prime_excel_format_id = "'.$excel_format.'" and cw_form_setting.prime_module_id = "'.$module_id.'" and cw_util_excel_format_line.trans_status = 1';		
				$excel_format        = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
				$excel_format_result = $excel_format->result();
				$excel_format->next_result();
				if(!$excel_format_result){
					return json_encode(array('success' => false, 'message' => "Please map excel cell column before import"));
				}else{
					try{
						$excel_obj = PHPExcel_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_date     = $sheet->getCell("$col_key$i")->getValue();	
									$unix_date      = $this->unix_convertion($excel_date);
									if($unix_date <= 0){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
											$msg_line = "Please enter valid date... Please map The Date Format Like (DD/MM/YYYY)";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}
								}
								$i++;
							}
						}
					}
					
					$err_column_count = count($err_column_array['error']);
					if((int)$err_column_count > 0){
						$table_info = $this->get_excel_error_ui($err_column_tabview);
						echo json_encode(array('success'=>false,'message'=>"Column Wise Error",'table_info'=>$table_info));
						exit();
					}else{
						//Unique field check
						$err_column_tabview  = array();
						$array_uniq 		= array();
						foreach ($excel_format_result as $key => $value) {
							$label_name 		= $value->label_name;
							$view_name 			= $value->view_name;
							$unique_field 		= $value->unique_field;
							$excel_line_value 	= $value->excel_line_value;
							$multi_get_cell_value = $sheet->rangeToArray("$excel_line_value$excel_row_start:$excel_line_value$total_rows", NULL, TRUE, TRUE, TRUE);

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

									if((int)$exist_count > 0){
										$err_column_array['error']["$excel_line_value$current_key"] = $view_name;
										$msg_line = "Data already exists for this Column";
										$err_column_tabview['error']["$excel_line_value$current_key"]  = $view_name." ".$msg_line;
									}
								}
							}
						}
						// get module unique column 
						$uniq_field_qry  = 'select view_name,label_name from  cw_form_setting where cw_form_setting.prime_module_id = "'.$module_id.'" and input_view_type IN(1,2) and field_show = 1 and unique_field = 1 and trans_status = 1';
						$uniq_field_info = $this->db->query("CALL sp_a_run ('SELECT','$uniq_field_qry')");
						$uniq_field_rslt = $uniq_field_info->result_array();
						$uniq_field_info->next_result();
						$uniq_field_rslt = array_reduce($uniq_field_rslt, function($result, $arr){	
							    $result[$arr['label_name']] = $arr;
							    return $result;
							}, array());
						$uniq_result 	 = array_diff_key($uniq_field_rslt,$array_uniq);
						if((int)$import_type === 1){
							foreach ($uniq_result as $uniq_key => $uniq_val) {
								$label_name 	= $uniq_val['label_name'];
								$err_column_array['error']["label_name"] = $uniq_val['view_name'];
								$msg_line = "Unique Field Column Missing";
								$err_column_tabview['error'][$uniq_val['view_name']]  = $uniq_val['view_name']." ".$msg_line;
							}
						}
						$err_column_count = count($err_column_array['error']);
						$err_column       = implode(",",(array_unique($err_column_array['error'])));
						if((int)$err_column_count > 0){
							$table_info = $this->get_excel_error_ui($err_column_tabview);
							echo json_encode(array('success'=>false,'message'=>"Column Wise Error",'table_info'=>$table_info));
							exit();
						}
						
						$status_array	= array();
						for($row =$excel_row_start; $row <= $total_rows; $row++) {
							$prime_column_val = "";
							$prime_cell_val   = "";
							$exist_val        = "";
							$status_info = array();
							$status_info["Excel Row"] = $row;
							$sts = TRUE;
							$email_sts = TRUE;
							foreach($excel_format_result as $excel_info){
								$field_isdefault        = (int)$excel_info->field_isdefault;
								$mandatory_field        = (int)$excel_info->mandatory_field;
								$field_type             = (int)$excel_info->field_type;
								$pick_table             = $excel_info->pick_table;
								$pick_list_type         = (int)$excel_info->pick_list_type;
								$pick_list_import       = (int)$excel_info->pick_list_import;
								$pick_list              = $excel_info->pick_list;
								$excel_line_column_name = $excel_info->excel_line_column_name;
								$excel_line_value       = $excel_info->excel_line_value;
								$get_cell_value         = ucwords(trim($sheet->getCell("$excel_line_value$row")->getValue()));
	                            if($get_cell_value){
									//FOR MOBILE NUMBER
									 if($field_type === 11){
										$length = strlen($get_cell_value);
										$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('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getValue())));
									}else
									if($field_type === 13){
										$get_datetime = trim(date('Y-m-d H:i:s',PHPExcel_Shared_Date::ExcelToPHP($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 === 1){
												if($pick_table !== $this->prime_table){
													$pick_id     = (int)$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     = (int)$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->get_leave_financial_details();
		$prime_financial_id    = $financial_info[0]->prime_leave_financial_year_id;	
		$starting_date         = date('Y-m-d',strtotime($financial_info[0]->starting_date));	
		$ending_date           = date('Y-m-d',strtotime($financial_info[0]->ending_date));	

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

		$salary_start_date     = date('Y-m-d',strtotime($salary_info_arr['salary_start_date']));
		$salary_end_date       = date('Y-m-d',strtotime($salary_info_arr['salary_end_date']));
		$emp_name_arr          = ""; 
		$shift_import_arr      = "";
		$shift_name_arr        = "";
		$created_on            = date('Y-m-d H:i:s');
		$filename = dirname(__FILE__)."/php_excel/PHPExcel/IOFactory.php";
		include($filename);
		if($import_id < 0){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}
		
		$excel_path_qry    = 'select * from cw_import where import_id = "'.$import_id.'"';
		$excel_path_info   = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
		$excel_path_result = $excel_path_info->result();
		$excel_path_info->next_result();
		if(!$excel_path_result){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}else{
			$excel_file_path    = $excel_path_result[0]->excel_file_path;
			$module_id          = $excel_path_result[0]->module_id;
			$excel_format       = $excel_path_result[0]->excel_format;
			$excel_sheet_name   = (int)$excel_path_result[0]->excel_sheet_name;
			$excel_row_start    = (int)$excel_path_result[0]->excel_start_row;
			$excel_row_end      = (int)$excel_path_result[0]->excel_end_row;
			
			$format_qry 	= 'select * from cw_util_excel_format where prime_excel_format_id = "'.$excel_format.'" and cw_util_excel_format.trans_status = 1';
			$format_info    = $this->db->query("CALL sp_a_run ('SELECT','$format_qry')");
			$format_rslt    = $format_info->result();
			$format_info->next_result();
			if(!$format_rslt){
				return json_encode(array('success' => false, 'message' => "Please add excel format before import"));
			}else{
				//GET EMPLOYEE DETAILS FROM EMPLOYEE MASTER
				$emp_name_qry    = 'select employee_code,role as category,emp_name,date_of_joining,department,approve_type,first_level_approval,second_level_approval,termination_status,resignation_date from cw_employees where cw_employees.role = "'.$category.'" and (cw_employees.termination_status = 0 or cw_employees.resignation_date >= "'.$salary_start_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 employee_code,att_date,entry_flag,update_flag,date_format(cw_time_entry.punch_in, "%H:%i") as punch_in,date_format(cw_time_entry.punch_out, "%H:%i") as punch_out,if(cw_time_entry.early_in > 0, time_format(concat(floor(cw_time_entry.early_in/60),":",lpad(mod(cw_time_entry.early_in,60),2,"0")),"%H:%i"), cw_time_entry.early_in) as early_in,if(cw_time_entry.excess_out > 0, time_format(concat(floor(cw_time_entry.excess_out/60),":",lpad(mod(cw_time_entry.excess_out,60),2,"0")),"%H:%i"), cw_time_entry.excess_out) as excess_out,if(cw_time_entry.total_excess_hours > 0, time_format(concat(floor(cw_time_entry.total_excess_hours/60),":",lpad(mod(cw_time_entry.total_excess_hours,60),2,"0")),"%H:%i"), cw_time_entry.total_excess_hours) as total_excess_hours,whole_day_status,shift_id,cw_shift_master.shift_name,cw_shift_master.from_time,cw_shift_master.to_time,cw_shift_master.shift_status,cw_shift_master.shift_start,cw_shift_master.shift_end,cw_shift_master.in_time as import_in_time,cw_shift_master.out_time as import_out_time from cw_time_entry inner join cw_shift_master on cw_shift_master.prime_shift_master_id = cw_time_entry.shift_id where att_date between "'.$salary_start_date.'" and "'.$salary_end_date.'" and cw_time_entry.trans_status = 1';
				$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());	

				$exist_column_name = explode(",",$format_rslt[0]->exist_column_name);
				$excel_format_qry 	= 'select field_type,pick_table,pick_list_type,pick_list_import,pick_list,mandatory_field,field_isdefault,excel_line_column_name,excel_line_value from cw_util_excel_format_line inner join cw_form_setting on label_name = excel_line_column_name where excel_line_module_id = "'.$module_id.'" and prime_excel_format_id = "'.$excel_format.'" and cw_form_setting.prime_module_id = "'.$module_id.'" and cw_util_excel_format_line.trans_status = 1';			
				$excel_format        = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
				$excel_format_result = $excel_format->result();
				$excel_format->next_result();
				if(!$excel_format_result){
					return json_encode(array('success' => false, 'message' => "Please map excel cell column before import"));
				}else{
					try{
						$excel_obj = PHPExcel_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();
					$excel_exist_arr      = array();
					$del_req_ins_arr      = array();
					$prime_query_value    = "";
					$prime_upd_value      = "";
					
					for($row =$excel_row_start; $row <= $total_rows; $row++) {
						$prime_column_val = "";
						$prime_cell_val   = "";
						$exist_val        = "";
						$status_info      = array();
						$status_info["Excel Row"] = $row;
						$sts              = TRUE;
						$email_sts        = TRUE;
						$picklist_sts     = TRUE;
						$app_sts          = TRUE;
						$exist_count      = 0;
						foreach($excel_format_result as $excel_info){
							$field_isdefault        = (int)$excel_info->field_isdefault;
							$mandatory_field        = (int)$excel_info->mandatory_field;
							$field_type             = (int)$excel_info->field_type;
							$pick_table             = $excel_info->pick_table;
							$pick_list_type         = (int)$excel_info->pick_list_type;
							$pick_list_import       = (int)$excel_info->pick_list_import;
							$pick_list              = $excel_info->pick_list;
							$excel_line_column_name = $excel_info->excel_line_column_name;
							$excel_line_value       = $excel_info->excel_line_value;

							$get_cell_value         = ucwords(trim($sheet->getCell("$excel_line_value$row")->getValue()));
                            if($get_cell_value){
								//FOR MOBILE NUMBER
								 if($field_type === 11){
									$length = strlen($get_cell_value);
									$length_query = 'select field_length from cw_form_setting where cw_form_setting.prime_module_id = "'.$module_id.'" and cw_form_setting.field_type = 11';
									$length_data  = $this->db->query("CALL sp_a_run ('SELECT','$length_query')");
									$length_result = $length_data->result();
									$length_data->next_result();
									$field_length = $length_result[0]->field_length;
									if($field_length != $length){
										$sts = FALSE;
									}
								}else 
								if($field_type === 12){
									//FOR EMAIL
									$email = $get_cell_value;
									if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
										$email_sts = FALSE;
									}
								}else
								if($field_type === 4){
									// FOR DATE
									$get_cell_value = trim(date('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getValue())));
								}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';
										}	
										$pick_data  = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
										$pick_result = $pick_data->result();
										$pick_count  = $pick_data->num_rows();
										$pick_data->next_result();
										if((int)$pick_count === 0){
											$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
											$exist_count     = 1;
										}else
										if((int)$pick_count === 1){
											if($pick_table !== $this->prime_table){
												$pick_id     = (int)$pick_result[0]->$pick_list_val_1;
												$pick_status = (int)$pick_result[0]->trans_status;
												if($pick_status === 0){
													$upd_query  = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = '.$pick_id;
													$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
												}
												$get_cell_value = $pick_id;
											}
										}
									}else
									if($pick_list_type === 2){
										$pick_list_val_1 = $pick_table."_id";
										$pick_list_val_2 = $pick_table."_value";
										$pick_list_val_3 = $pick_table."_status";
										$pick_query = 'select * from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'" and '.$pick_table.'.trans_status = 1';
										$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
										$pick_result = $pick_data->result();
										$pick_count  = $pick_data->num_rows();
										$pick_data->next_result();
										if((int)$pick_count === 0){
											$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
											$exist_count    = 1;
										}else
										if((int)$pick_count === 1){
											$pick_id        = (int)$pick_result[0]->$pick_list_val_1;
											$pick_status    = (int)$pick_result[0]->$pick_list_val_3;
											if($pick_status === 0){
												$upd_query  = 'update '.$pick_table.' set '.$pick_list_val_3.' = 1 where '.$pick_list_val_1.' = '.$pick_id;
												$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
											}
											$get_cell_value = $pick_id;
										}
									}
								}
								if($field_isdefault === 1){
									if($excel_line_column_name === 'employee_code'){
										$employee_code     = $get_cell_value;
										$emp_code_col_name = $excel_line_value;
										$employee_name     = $emp_name_arr[$employee_code]['emp_name'];
										$check_emp_code    = $emp_name_arr[$employee_code]['employee_code'];
										$category          = $emp_name_arr[$employee_code]['category'];
										$emp_doj           =  date("Y-m-d",strtotime($emp_name_arr[$employee_code]['date_of_joining']));
										$approve_type      = $emp_name_arr[$employee_code]['approve_type'];
										$department        = $emp_name_arr[$employee_code]['department'];
										$active_sts        = (int)$emp_name_arr[$employee_code]['termination_status'];
										$resign_date       = date("Y-m-d",strtotime($emp_name_arr[$employee_code]['resignation_date']));
										$first_level       = $emp_name_arr[$employee_code]['first_level_approval'];
										$second_level      = $emp_name_arr[$employee_code]['second_level_approval'];
										$applied_on        = date('Y-m-d');
										
									}
									if($excel_line_column_name === 'shift_name'){
										$shift_name        = $get_cell_value;
									}
									if($excel_line_column_name === "entry_date"){
										$entry_date           = date('Y-m-d',strtotime($get_cell_value));
										$entry_date_col_name  = $excel_line_value;
									}
									if($excel_line_column_name === "ot_in_time"){
										$in_time_col_name     = $excel_line_value;
										if($get_cell_value === "" || $get_cell_value === "00:00"){
											(int)$exist_count += 1;
											if($exist_count === 1){
												$err_column_array['error']["$excel_line_value$row"] = "OT In Time should not Zero or Empty..!!";
												$exist_count++;
											}
										}else{
											$get_datetime = trim(date('H:i',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
											$newhours     = date('H:i', strtotime($get_datetime. ' -5 hours'));
											$ot_in_time   = date('H:i', strtotime($newhours. ' -30 minutes'));
										}
									}
									if($excel_line_column_name === "ot_out_time"){
										$out_time_col_name     = $excel_line_value;
										if($get_cell_value === "" || $get_cell_value === "00:00"){
											(int)$exist_count += 1;
											if($exist_count === 1){
												$err_column_array['error']["$excel_line_value$row"] = "OT Out Time should not Zero or Empty..!!";
												$exist_count++;
											}
										}else{
											$get_datetime = trim(date('H:i',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
											$newhours     = date('H:i', strtotime($get_datetime. ' -5 hours'));
											$ot_out_time  = date('H:i', strtotime($newhours. ' -30 minutes'));
										}
									}
									if($excel_line_column_name === "reason"){
										$reason         = $get_cell_value;
									}
								}
							}
						}
						if(!$check_emp_code){
							$err_column_array['error']["$emp_code_col_name$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;

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

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

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

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

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

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

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

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

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

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

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

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

													$import_in_date   = date("Y-m-d H:i",strtotime($entry_date.' '.$import_in_time));
													$import_out_date  = date("Y-m-d H:i",strtotime($entry_date.' '.$import_out_time));
													$punch_in_date    = date("Y-m-d H:i",strtotime($entry_date.' '.$punch_in));
													$punch_out_date   = date("Y-m-d H:i",strtotime($entry_date.' '.$punch_out));
													$ot_in_date       = date("Y-m-d H:i",strtotime($entry_date.' '.$ot_in_time));
													$ot_out_date      = date("Y-m-d H:i",strtotime($entry_date.' '.$ot_out_time));

													$total_excess_hrs = "";
													if($time_entry_arr[$employee_code][$entry_date]['total_excess_hours']){
														$total_excess_hrs = date("H:i",strtotime($time_entry_arr[$employee_code][$entry_date]['total_excess_hours']));
													}else{
														(int)$exist_count += 1;
														if($exist_count === 1){
															$err_column_array['error']["$entry_date_col_name$row"] = "In this Attenedance Date Total OT Hours Should not Empty or Zero Please Check it..!!";
															$exist_count++;
														}
													}
													if($punch_in && $punch_out && $ot_in_time && $ot_out_time && $total_excess_hrs){
														if($shift_start === 2){
															$import_in_date  = date("Y-m-d H:i",strtotime("+1 day",strtotime($entry_date.' '.$import_in_time)));
															$punch_in_date   =  date("Y-m-d H:i",strtotime("+1 day",strtotime($entry_date.' '.$punch_in)));
															$ot_in_date      =  date("Y-m-d H:i",strtotime("+1 day",strtotime($entry_date.' '.$ot_in_time)));
														}else
														if($shift_start === 3){
															$import_in_date = date("Y-m-d H:i",strtotime("-1 day",strtotime($entry_date.' '.$import_in_time)));
															if($import_in_time <= $punch_in){
																$punch_in_date    =  date("Y-m-d H:i",strtotime("-1 day",strtotime($entry_date.' '.$punch_in)));
															}
															if($import_in_time <= $ot_in_time){
																$ot_in_date  = date("Y-m-d H:i",strtotime("-1 day",strtotime($entry_date.' '.$ot_in_time)));
															}	
																
														}
														if($shift_end === 2){
															$import_out_date = date("Y-m-d H:i",strtotime("+1 day",strtotime($entry_date.' '.$import_out_time)));
															if($import_out_time >= $punch_out){
																$punch_out_date        = date("Y-m-d H:i",strtotime("+1 day",strtotime($entry_date.' '.$punch_out)));
															}
															if($import_out_time >= $ot_out_time){
																$ot_out_date  = date("Y-m-d H:i",strtotime("+1 day",strtotime($entry_date.' '.$ot_out_time)));
															}
														}else
														if($shift_end === 3){
															$import_out_date = date("Y-m-d H:i",strtotime("-1 day",strtotime($entry_date.' '.$ot_out_time)));
															$punch_out_date  = date("Y-m-d H:i",strtotime("-1 day",strtotime($entry_date.' '.$punch_out)));
															$ot_out_date  = date("Y-m-d H:i",strtotime("-1 day",strtotime($entry_date.' '.$ot_out_time)));
															
														}
														if($punch_in_date > $ot_in_date){
															(int)$exist_count += 1;
															if($exist_count === 1){
																$err_column_array['error']["$in_time_col_name$row"] = "OT In Time should not be Less than Punch In Time..!!";
																$exist_count++;
															}
														}else
														if($punch_out_date <= $ot_in_date){
															(int)$exist_count += 1;
															if($exist_count === 1){
																$err_column_array['error']["$in_time_col_name$row"] = "Ot In Time Should not be Greater than Punch Out Time..!!";
																$exist_count++;
															}
														}else
														if($punch_in_date >= $ot_out_date){
															(int)$exist_count += 1;
															if($exist_count === 1){
																$err_column_array['error']["$out_time_col_name$row"] = "OT Out Time should not be Less than Punch In Time..!!";
																$exist_count++;
															}
														}else
														if($punch_out_date < $ot_out_date){
															(int)$exist_count += 1;
															if($exist_count === 1){
																$err_column_array['error']["$out_time_col_name$row"] = "OT Out Time should not be Greater than Punch Out Time..!!";
																$exist_count++;
															}
														}else{
															if(($entry_flag === "U" || $update_flag === "U") && ($entry_flag !== "W" && $update_flag !== "W")){
																(int)$exist_count += 1;
																if($exist_count === 1){
																	$err_column_array['error']["$entry_date_col_name$row"] = "On this Attendance Date You are not Eligible for Apply OT Request..!Please Check it?..!!";
																	$exist_count++;
																}
															}else{
																if($ot_in_date && $ot_out_date){
																	//to calculate total hours with two dates
																	$date_arr    = date_diff(date_create($ot_in_date), date_create($ot_out_date));
																	$time_hr     = $date_arr->h;
																	$time_min    = $date_arr->i;
																	//total_hours get in hours and minutes format
																	$total_hours = date("H:i",strtotime($time_hr.":".$time_min));

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

																			$prime_column_val       = "employee_code,category,date_of_joining,department,approval_type,first_level_approval,second_level_approval,applied_on,entry_date,shift_name,in_time,out_time,ot_in_time,ot_out_time,early_coming,excess_out,excess_work,over_time,ot_type,shift_status,first_approval_status,second_approval_status,approval_status,financial_setting_id,reason,trans_created_by,trans_created_date";
							
																			$request_ins_qry  = "insert into cw_overtime_request ($prime_column_val) VALUES ($prime_req_value)";					
																			$request_ins_info = $this->db->query("CALL sp_a_run ('INSERT','$request_ins_qry')");
																			$request_ins_rslt = $request_ins_info->result();
																			$request_ins_info->next_result();

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

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

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

																				//OT ENTRY INSERT QRY	
																				$ot_entry_ins_val .= '"'.$insert_id.'","'.$prime_financial_id.'","'.$category.'","'.$employee_code.'","'.$shift_name.'","'.$shift_status.'","'.$entry_date.'","'.$punch_in.'","'.$punch_out.'","'.$ot_in_time.'","'.$ot_out_time.'","'.$early_in.'","'.$excess_out.'","'.$total_hours.'","00:00:00","1","1","'.$this->logged_id.'","'.$created_on.'"),(';
	
																				$status_info['Status'] = "Inserted to DB";
																				$status_array[] = $status_info;
																			}	
																		}
																	}
																}
															}
														}	
													}
												}
											}
										}	
									}
								}else{
									$err_column_array['error']["$emp_code_col_name$row"] = "Please Add Date of Joining for this Employee..!!";
								}
							}		
						}
					}
					$err_column_count = count($err_column_array['error']);
	
					if((int)$err_column_count > 0){
						//delete a wrong insert data from ot request table
						$del_req_ins_id = implode(',',$del_req_ins_arr);
						if($del_req_ins_id){
							$delete_query  = 'DELETE FROM cw_overtime_request  WHERE  prime_overtime_request_id in ('. $del_req_ins_id .')';
							$this->db->query("CALL sp_a_run ('RUN','$delete_query')");
						}
						$table_info = $this->get_excel_error_ui($err_column_array);

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

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

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

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

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

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

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

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

					if((int)$employee_count <= 0){
						echo json_encode(array('success'=>false,'message'=>"Please check Employee Code Column in your Excel Sheet...",'table_info'=>""));
						exit(0);
					}
					$employee_codes     = trim(implode('","',$employee_codes_arr));
	                
					//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());

					$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;
						foreach($excel_format_result as $excel_info){
							$field_isdefault        = (int)$excel_info->field_isdefault;
							$mandatory_field        = (int)$excel_info->mandatory_field;
							$field_type             = (int)$excel_info->field_type;
							$pick_table             = $excel_info->pick_table;
							$pick_list_type         = (int)$excel_info->pick_list_type;
							$pick_list_import       = (int)$excel_info->pick_list_import;
							$pick_list              = $excel_info->pick_list;
							$excel_line_column_name = $excel_info->excel_line_column_name;
							$excel_line_value       = $excel_info->excel_line_value;

							$get_cell_value         = ucwords(trim($sheet->getCell("$excel_line_value$row")->getValue()));
                            if($get_cell_value){
								if($field_type === 12){
									//FOR EMAIL
									$email = $get_cell_value;
									if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
										$email_sts = FALSE;
									}
								}else
								if($field_type === 4){
									$excel_date     = $sheet->getCell("$excel_line_value$row")->getValue();	
									$unix_date      = $this->unix_convertion($excel_date);
									$get_cell_value = gmdate("Y-m-d", $unix_date);
									if($unix_date <= 0){
										$err_column_array['error']["$excel_line_value$row"] = "Please enter valid date... Please map The Date Format Like (DD/MM/YYYY)";
									}else
									if(($starting_date > $get_cell_value) || ($ending_date < $get_cell_value)){
										$err_column_array['error']["$excel_line_value$row"]   = "Date Should be inbetween Leave Financial Start date and End date..!..!";
									}
								}else
								if($field_type === 13){
									$get_cell_value = trim(date('Y-m-d H:i:s',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';
										}	
										$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     = (int)$pick_result[0]->$pick_list_val_1;
												$pick_status = (int)$pick_result[0]->trans_status;
												if($pick_status === 0){
													$upd_query  = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = '.$pick_id;
													$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
												}
												$get_cell_value = $pick_id;
											}
										}
									}else
									if($pick_list_type === 2){
										$pick_list_val_1 = $pick_table."_id";
										$pick_list_val_2 = $pick_table."_value";
										$pick_list_val_3 = $pick_table."_status";
										$pick_query = 'select * from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'" and '.$pick_table.'.trans_status = 1';
										$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
										$pick_result = $pick_data->result();
										$pick_count  = $pick_data->num_rows();
										$pick_data->next_result();
										if((int)$pick_count === 0){
											$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
										}else
										if((int)$pick_count === 1){
											$pick_id     = (int)$pick_result[0]->$pick_list_val_1;
											$pick_status = (int)$pick_result[0]->$pick_list_val_3;
											if($pick_status === 0){
												$upd_query  = 'update '.$pick_table.' set '.$pick_list_val_3.' = 1 where '.$pick_list_val_1.' = '.$pick_id;
												$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
											}
											$get_cell_value = $pick_id;
										}
									}
								}
								if($field_isdefault === 1){
									if($excel_line_column_name === 'employee_code'){
										$emp_code_col_name    = $excel_line_value;
										$employee_code        = $get_cell_value;
										$employee_name        = $emp_name_arr[$employee_code]['emp_name'];
										$check_emp_code       = $emp_name_arr[$employee_code]['employee_code'];
										if(!$check_emp_code){
											$err_column_array['error']["$excel_line_value$row"] = "This Employee Code ($employee_code) or Employee Name not Present in the Employee Master? Please Check it..!";
										}
									}else
									if($excel_line_column_name === 'shift_name'){
										$shift_name_col_name  = $excel_line_value;
										$shift_name           = $get_cell_value;
									}else
									if($excel_line_column_name === "from_date"){
										$from_date     = $get_cell_value;
									}else
									if($excel_line_column_name === "to_date"){
										$to_date       = $get_cell_value;
										$after_to_date = date('Y-m-d',strtotime("+1 day",strtotime($to_date)));

									}									
									if(empty($exist_column_name)){
										 if($mandatory_field === 1){
											$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
										}
									}else{
										if(in_array($excel_line_column_name,$exist_column_name)){
											$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
										}
									}
								}
							}
						}
						if($employee_code && $from_date && $to_date && $shift_name){
							//QUERY FOR CHECK EXIST DATA FROM SHIFT IMPORT TABLE 
							$shift_import_exist_qry  = 'select employee_code,shift_date,prime_shift_import_id as prime_id from cw_shift_import where trans_status = 1 and cw_shift_import.employee_code = "'.$employee_code.'" and shift_date between "'.$from_date.'" and "'.$to_date.'" and financial_setting_id ="'.$prime_financial_id.'"';
							$shift_import_exist_info = $this->db->query("CALL sp_a_run ('RUN','$shift_import_exist_qry')");
							$shift_import_exist_rslt = $shift_import_exist_info->result_array();
							$shift_import_exist_info->next_result();

							$shift_import_arr = array_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'];
								$prime_shift_id    = $shift_import_arr[$employee_code][$shift_date]['prime_id'];

								//CHECK A VALID SHIFT IMPORT OR NOT
								$check_shift_name  = $shift_name_arr[$shift_name];
								//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']["$excel_line_value$row"] = "Shift Date Should be Greater than Date of Joining Please Check it..!!";
										$exist_count++;
									}
								}else
								if(!$check_shift_name){
									(int)$exist_count += 1;
									if($exist_count === 1){
										$err_column_array['error']["$excel_line_value$row"] = "Invalid Shift Name Please Check it!!";
										$exist_count++;
									}
								}else
								if($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){
		$leave_financial_info  = $this->get_leave_financial_details();
		$prime_financial_id    = $leave_financial_info[0]->prime_leave_financial_year_id;
		$starting_date         = date('Y-m-d',strtotime($leave_financial_info[0]->starting_date));	
		$ending_date           = date('Y-m-d',strtotime($leave_financial_info[0]->ending_date));	
		$emp_name_arr          = "";
		$time_entry_arr        = "";
		$leave_entry_arr       = "";
		$permission_entry_arr  = "";
		$on_duty_entry_arr     = "";
		$shift_import_arr      = ""; 
		$weekoff_import_arr    = "";
		$weekoff_id_arr        = "";
		$filename              = dirname(__FILE__)."/php_excel/PHPExcel/IOFactory.php";
		include($filename);
		if($import_id < 0){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}		
		$excel_path_qry    = 'select * from cw_import where import_id = "'.$import_id.'"';
		$excel_path_info   = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
		$excel_path_result = $excel_path_info->result();
		$excel_path_info->next_result();
		
		if(!$excel_path_result){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}else{
			$excel_file_path    = $excel_path_result[0]->excel_file_path;
			$module_id          = $excel_path_result[0]->module_id;
			$excel_format       = $excel_path_result[0]->excel_format;
			$excel_sheet_name   = (int)$excel_path_result[0]->excel_sheet_name;
			$excel_row_start    = (int)$excel_path_result[0]->excel_start_row;
			$excel_row_end      = (int)$excel_path_result[0]->excel_end_row;
			
			$format_qry 	= 'select * from cw_util_excel_format where prime_excel_format_id = "'.$excel_format.'" and cw_util_excel_format.trans_status = 1';
			$format_info    = $this->db->query("CALL sp_a_run ('SELECT','$format_qry')");
			$format_rslt    = $format_info->result();
			$format_info->next_result();
			
			if(!$format_rslt){
				return json_encode(array('success' => false, 'message' => "Please add excel format before import"));
			}else{
				$exist_column_name = explode(",",$format_rslt[0]->exist_column_name);
				$excel_format_qry 	= 'select field_type,pick_table,pick_list_type,pick_list_import,pick_list,mandatory_field,field_isdefault,excel_line_column_name,excel_line_value from cw_util_excel_format_line inner join cw_form_setting on label_name = excel_line_column_name where excel_line_module_id = "'.$module_id.'" and prime_excel_format_id = "'.$excel_format.'" and cw_form_setting.prime_module_id = "'.$module_id.'" and cw_util_excel_format_line.trans_status = 1';			
				$excel_format        = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
				$excel_format_result = $excel_format->result();
				$excel_format->next_result();

				if(!$excel_format_result){
					return json_encode(array('success' => false, 'message' => "Please map excel cell column before import"));
				}else{
					try{
						$excel_obj = PHPExcel_IOFactory::load($excel_file_path);
					}catch(Exception $e){
						die('Error loading file "' . pathinfo($excel_file_path, PATHINFO_BASENAME). '": ' . $e->getMessage());
						return json_encode(array('success' => false, 'message' => "Invalid file or path"));
					}
					$sheet          = $excel_obj->getSheet($excel_sheet_name);
					if($excel_row_end){
						$total_rows = $excel_row_end;
					}else{
						$total_rows = $sheet->getHighestRow();
					}

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

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

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

				$emp_name_arr      = array_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.employee_code in ("'.$employee_codes.'")';
				$time_entry_info   = $this->db->query("CALL sp_a_run ('RUN','$time_entry_qry')");
				$time_entry_result = $time_entry_info->result_array();
				$time_entry_info->next_result();

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

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

				$leave_entry_arr    = array_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.employee_code in ("'.$employee_codes.'")';
				$permission_entry_info   = $this->db->query("CALL sp_a_run ('RUN','$permission_entry_qry')");
				$permission_entry_result = $permission_entry_info->result_array();
				$permission_entry_info->next_result();

				$permission_entry_arr    = array_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.employee_code in ("'.$employee_codes.'")';
				$on_duty_entry_info   = $this->db->query("CALL sp_a_run ('RUN','$on_duty_entry_qry')");
				$on_duty_entry_result = $on_duty_entry_info->result_array();
				$on_duty_entry_info->next_result();

				$on_duty_entry_arr    = array_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 WEEKOFF IMPORT TABLE 
				$weekoff_import_exist_qry   = 'select prime_weekoff_import_id,employee_code,weekoff_date,weekoff_type from cw_weekoff_import where trans_status = 1 and financial_setting_id ="'.$prime_financial_id.'" and employee_code in ("'.$employee_codes.'")';
				$weekoff_import_exist_info  = $this->db->query("CALL sp_a_run ('RUN','$weekoff_import_exist_qry')");
				$weekoff_import_exist_result = $weekoff_import_exist_info->result_array();
				$weekoff_import_exist_info->next_result();
				$weekoff_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());
				$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('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getValue())));
								$format         = "Y-m-d";

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

								$date_format_sts  = $date && $date->format($format) === $get_cell_value;
								if(!$date_format_sts){
									$err_column_array['error']["$excel_line_value$row"]   = "Invalid Date Format..Please Map Date Format like (DD/MM/YYYY)..!";
								}else
								if(($starting_date > $get_cell_value) || ($ending_date < $get_cell_value)){
									$err_column_array['error']["$excel_line_value$row"]   = "Date Should be inbetween Leave Financial Start date and End date..!..!";
								}
							}else
							if($field_type === 13){
								$get_cell_value = trim(date('Y-m-d H:i:s',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.'"';
									}	
									$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     = (int)$pick_result[0]->$pick_list_val_1;
											$pick_status = (int)$pick_result[0]->trans_status;
											if($pick_status === 0){
												$upd_query  = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = '.$pick_id;
												$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
											}
											$get_cell_value = $pick_id;
										}
									}
								}else
								if($pick_list_type === 2){
									$pick_list_val_1 = $pick_table."_id";
									$pick_list_val_2 = $pick_table."_value";
									$pick_list_val_3 = $pick_table."_status";
									$pick_query = 'select * from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
									$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
									$pick_result = $pick_data->result();
									$pick_count  = $pick_data->num_rows();
									$pick_data->next_result();
									if((int)$pick_count === 0){
										$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
									}else
									if((int)$pick_count === 1){
										$pick_id     = (int)$pick_result[0]->$pick_list_val_1;
										$pick_status = (int)$pick_result[0]->$pick_list_val_3;
										if($pick_status === 0){
											$err_column_array['error']["$excel_line_value$row"] = "Invalid $get_cell_value";
										}
										$get_cell_value = $pick_id;
									}
								}
							}
							if($field_isdefault === 1){
								if($excel_line_column_name === 'employee_code'){
									$emp_code_col_name  = $excel_line_value;
									$employee_code      = $get_cell_value;
									$employee_name      = $emp_name_arr[$employee_code]['emp_name'];
									$check_emp_code     = $emp_name_arr[$employee_code]['employee_code'];
									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")
						);
					}
					$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'];
						//CHECK A VALID WEEKOFF TYPE FOR TO IMPORT OR NOT
						$check_weekoff_type     = $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 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){
		$leave_financial_info  = $this->get_leave_financial_details();
		$prime_financial_id    = $leave_financial_info[0]->prime_leave_financial_year_id;
		$starting_date         = date('Y-m-d',strtotime($leave_financial_info[0]->starting_date));	
		$ending_date           = date('Y-m-d',strtotime($leave_financial_info[0]->ending_date));	
		//CATEGORY BASED SALARY START DATE AND END DATE DETAILS
		$salary_info_arr       = $this->salary_start_end_info($category,$process_month);

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

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

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

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

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

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

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

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

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

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

				$man_punch_exist_arr  = array_reduce($man_punch_exist_rslt, function ($result, $arr){
				    $result[$arr['employee_code']][$arr['in_date']] = $arr['day_type'];
				    return $result;
				}, array());	
				
				$exist_column_name  = explode(",",$format_rslt[0]->exist_column_name);
				$excel_format_qry 	= 'select field_type,pick_table,pick_list_type,pick_list_import,pick_list,mandatory_field,field_isdefault,excel_line_column_name,excel_line_value from cw_util_excel_format_line inner join cw_form_setting on label_name = excel_line_column_name where excel_line_module_id = "'.$module_id.'" and prime_excel_format_id = "'.$excel_format.'" and cw_form_setting.prime_module_id = "'.$module_id.'" and cw_util_excel_format_line.trans_status = 1';			
				$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 = PHPExcel_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('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getValue())));
									$format           = "Y-m-d";

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

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

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

							//SHIFT IMPORT CHECK PROCESS
							$shift_import_name     = $shift_master_import_arr[$employee_code][$punch_date]['shift_name'];
							$shift_status          = $shift_master_import_arr[$employee_code][$punch_date]['shift_status'];
							$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;
						}
						if($rslt){
		                    $table_info = $this->get_excel_import_ui($status_array);
							return json_encode(array('success'=>true,'message'=>"Successfully File Imported",'table_info'=>$table_info));
						}else{
							return json_encode(array('success'=>true,'message'=>" File Not Imported",'table_info'=>$table_info));
						}
					}
				}
			}
		}
	}
	//import validation and checking updated
	public function do_excel_leave_import($import_id){
		$leave_financial_info = $this->get_leave_financial_details();
		$prime_financial_id   = $leave_financial_info[0]->prime_leave_financial_year_id;
		$starting_date        = date('Y-m-d',strtotime($leave_financial_info[0]->starting_date));	
		$ending_date          = date('Y-m-d',strtotime($leave_financial_info[0]->ending_date));	
		$filename             = dirname(__FILE__)."/php_excel/PHPExcel/IOFactory.php";
		include($filename);
		if($import_id < 0){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}
		
		$excel_path_qry    = 'select * from cw_import where import_id = "'.$import_id.'"';
		$excel_path_info   = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
		$excel_path_result = $excel_path_info->result();
		$excel_path_info->next_result();
		if(!$excel_path_result){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}else{
			$excel_file_path    = $excel_path_result[0]->excel_file_path;
			$module_id          = $excel_path_result[0]->module_id;
			$excel_format       = $excel_path_result[0]->excel_format;
			$excel_sheet_name   = (int)$excel_path_result[0]->excel_sheet_name;
			$excel_row_start    = (int)$excel_path_result[0]->excel_start_row;
			$excel_row_end      = (int)$excel_path_result[0]->excel_end_row;
			
			$format_qry 	= 'select * from cw_util_excel_format where prime_excel_format_id = "'.$excel_format.'" and cw_util_excel_format.trans_status = 1';
			$format_info    = $this->db->query("CALL sp_a_run ('SELECT','$format_qry')");
			$format_rslt    = $format_info->result();
			$format_info->next_result();
			if(!$format_rslt){
				return json_encode(array('success' => false, 'message' => "Please add excel format before import"));
			}else{
				
				//$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();
	
				if(!$excel_format_result){
					return json_encode(array('success' => false, 'message' => "Please map excel cell column before import"));
				}else{
					try{
						$excel_obj = PHPExcel_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';
					$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;		
								}	
							}	
						}	
						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
						$leave_financial_info   = $this->get_leave_financial_details();
						$prime_financial_id     =  $leave_financial_info[0]->prime_leave_financial_year_id;	
						$starting_date          = date('Y-m-d',strtotime($leave_financial_info[0]->starting_date));	
						$ending_date            = date('Y-m-d',strtotime($leave_financial_info[0]->ending_date));	
						$error                  = 0;
						// $success_sts     = array();
						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('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getValue())));
										$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     = (int)$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_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     = (int)$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_line_value$row"] = "Invalid $get_cell_value";
													$message                 = "Invalid $get_cell_value";
													$status                  = FALSE;
													$picklist_sts            = FALSE;
												}else
												if($pick_status === 0 && $mandatory_field === 0){
													$upd_query  = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = '.$pick_id;
													$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
													$get_cell_value = $pick_id;
												}else
												if($pick_status === 1){
													$get_cell_value = $pick_id;
												}
											}
										}
									}
									if($field_isdefault === 1){
										if($excel_line_column_name === 'employee_code'){
											$employee_code     = $get_cell_value;
											$component_value   = $employees_arr[$employee_code]['role'];
											$emp_doj           = $employees_arr[$employee_code]['date_of_joining'];
											$category          = $employees_arr[$employee_code]['role'];
											if(!$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;
										}

										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)";
									$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";
										$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($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    =  $this->month_day_qry_fun($category);
										}
										//LEAVE COUNT CHECK ONLY FOR LEAVE OPENING YES LEAVE TYPE
										if($leave_type && $leave_opening === 1){
											$opening_arr[$employee_code][$leave_type] += $leave_count;

											//for we check used leve count from above array (because in loop from same employee count should be create in array for we check leave balance count)
											$check_leave_count    = $opening_arr[$employee_code][$leave_type];
											//Get Balance count from opening array
											$balance_leave_count  = $opening_balance_used_arr[$employee_code]["balance_".$leave_type];
											//balance count and leve import count check 
											if($balance_leave_count < $check_leave_count){
												$error = 1;
												$upper_leave_type        = strtoupper($leave_type);
												$err_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();

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

					//Unique field check
					$err_column_tabview  = array();
					$array_uniq 		= array();
					foreach ($excel_format_result as $key => $value) {
						$label_name 		= $value->label_name;
						$view_name 			= $value->view_name;
						$unique_field 		= $value->unique_field;
						$excel_line_value 	= $value->excel_line_value;
						$multi_get_cell_value = $sheet->rangeToArray("$excel_line_value$excel_row_start:$excel_line_value$total_rows", NULL, TRUE, TRUE, TRUE);

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

								if((int)$exist_count > 0){
									$err_column_array['error']["$excel_line_value$current_key"] = $view_name;
									$msg_line = "Data already exists for this Column";
									$err_column_tabview['error']["$excel_line_value$current_key"]  = $view_name." ".$msg_line;
								}
							}
						}
					}
					// get module unique column 
					$uniq_field_qry  = 'select view_name,label_name from  cw_form_setting where cw_form_setting.prime_module_id = "'.$module_id.'" and input_view_type IN(1,2) and field_show = 1 and unique_field = 1 and trans_status = 1';
					$uniq_field_info = $this->db->query("CALL sp_a_run ('SELECT','$uniq_field_qry')");
					$uniq_field_rslt = $uniq_field_info->result_array();
					$uniq_field_info->next_result();
					$uniq_field_rslt = array_reduce($uniq_field_rslt, function($result, $arr){	
						    $result[$arr['label_name']] = $arr;
						    return $result;
						}, array());
					$uniq_result 	 = array_diff_key($uniq_field_rslt,$array_uniq);
					if((int)$import_type === 1){
						foreach ($uniq_result as $uniq_key => $uniq_val) {
							$label_name 	= $uniq_val['label_name'];
							$err_column_array['error']["label_name"] = $uniq_val['view_name'];
							$msg_line = "Unique Field Column Missing";
							$err_column_tabview['error'][$uniq_val['view_name']]  = $uniq_val['view_name']." ".$msg_line;
						}
					}
					$err_column_count = count($err_column_array['error']);
					$err_column       = implode(",",(array_unique($err_column_array['error'])));
					if((int)$err_column_count > 0){
						$table_info = $this->get_excel_error_ui($err_column_tabview);
						echo json_encode(array('success'=>false,'message'=>"Column Wise Error",'table_info'=>$table_info));
						exit();
					}
					
					$status_array	= array();
					for($row =$excel_row_start; $row <= $total_rows; $row++) {
						$prime_column_val = "";
						$prime_cell_val   = "";
						$exist_val        = "";
						$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('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getValue())));
								}else
								if($field_type === 13){
									$get_date_time 	= $sheet->getCell("$excel_line_value$row")->getValue();
									$date 			= DateTime::createFromFormat('d/m/Y H:i:s A', $get_date_time);
									$get_cell_value = $date->format('Y-m-d H:i:s');
								}else
								// FOR PICKLIST CHECK
								if(($field_type === 5) || ($field_type === 7)){
									if($pick_list_type === 1){
										$pick_list_val   = explode(",",$pick_list);
										$pick_list_val_1 = $pick_list_val[0];
										$pick_list_val_2 = $pick_list_val[1];
										$pick_query = 'select '.$pick_list.',trans_status from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
										if($pick_list_import === 1){
											$pick_query = 'select '.$pick_list.',trans_status from '.$pick_table.' where '.$pick_list_val_1.' = "'.$get_cell_value.'"';	
										}else{
											$pick_query = 'select '.$pick_list.',trans_status from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
										}	
										$pick_data  = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
										$pick_result = $pick_data->result();
										$pick_count  = $pick_data->num_rows();
										$pick_data->next_result();
										if((int)$pick_count === 0 && $mandatory_field === 0){
											if($pick_table !== $this->prime_table){
												$ins_query  = 'insert into '.$pick_table.'('.$pick_list_val_2.') VALUES ("'.$get_cell_value.'")';
												$ins_info   = $this->db->query("CALL sp_a_run ('INSERT','$ins_query')");
												$ins_result = $ins_info->result();
												$ins_info->next_result();
												$get_cell_value  = $ins_result[0]->ins_id;
											}
										}else
										if((int)$pick_count === 0 && $mandatory_field === 1){
											$status_info["$excel_line_value$row"] = "Invalid $get_cell_value";
											$message               = "Invalid $get_cell_value";
											$status                = FALSE;
											$picklist_sts          = FALSE;
										}else
										if((int)$pick_count === 1){
											if($pick_table !== $this->prime_table){
												$pick_id     = (int)$pick_result[0]->$pick_list_val_1;
												$pick_status = (int)$pick_result[0]->trans_status;
												if($pick_status === 0 && $mandatory_field === 1){
													$status_info["$excel_line_value$row"] = "Invalid $get_cell_value";
													$message               = "Invalid $get_cell_value";
													$status                = FALSE;
													$picklist_sts          = FALSE;
												}else
												if($pick_status === 0 && $mandatory_field === 0){
													$upd_query  = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = '.$pick_id;
													$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
													$get_cell_value = $pick_id;
												}else
												if($pick_status === 1){
													$get_cell_value = $pick_id;
												}
											}
										}
									}else
									if($pick_list_type === 2){
										$pick_list_val_1 = $pick_table."_id";
										$pick_list_val_2 = $pick_table."_value";
										$pick_list_val_3 = $pick_table."_status";
										$pick_query = 'select * from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
										$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
										$pick_result = $pick_data->result();
										$pick_count  = $pick_data->num_rows();
										$pick_data->next_result();
										if((int)$pick_count === 0 && $mandatory_field === 0){
											$ins_query  = 'insert into '.$pick_table.'('.$pick_list_val_2.') VALUES ("'.$get_cell_value.'")';
											$ins_info   = $this->db->query("CALL sp_a_run ('INSERT','$ins_query')");
											$ins_result = $ins_info->result();
											$ins_info->next_result();
											$get_cell_value  = $ins_result[0]->ins_id;
										}else
										if((int)$pick_count === 0 && $mandatory_field === 1){
											$status_info["$excel_line_value$row"] = "Invalid $get_cell_value";
											$message               = "Invalid $get_cell_value";
											$status                = FALSE;
											$picklist_sts          = FALSE;
										}else
										if((int)$pick_count === 1){
											$pick_id     = (int)$pick_result[0]->$pick_list_val_1;
											$pick_status = (int)$pick_result[0]->$pick_list_val_3;
											if($pick_status === 0 && $mandatory_field === 1){
												$status_info["$excel_line_value$row"] = "Invalid $get_cell_value";
												$message               = "Invalid $get_cell_value";
												$status                = FALSE;
												$picklist_sts          = FALSE;
											}else
											if($pick_status === 0 && $mandatory_field === 0){
												$upd_query  = 'update '.$pick_table.' set trans_status = 1 where '.$pick_list_val_1.' = '.$pick_id;
												$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
												$get_cell_value = $pick_id;
											}else
											if($pick_status === 1){
												$get_cell_value = $pick_id;
											}
										}
									}
								}
								if($field_isdefault === 1){
									$get_cell_value    = str_replace("'",'^', $get_cell_value);
									$prime_column_val .= $excel_line_column_name . ",";
									$prime_cell_val   .= "\'" . $get_cell_value . "\',";
									if(empty($exist_column_name)){
										 if($mandatory_field === 1){
											$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
										}
									}else{
										if(in_array($excel_line_column_name,$exist_column_name)){
											$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
										}
									}
								}
							}
						}
						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 && $picklist_sts){
								$prime_column_val .= "trans_created_by,trans_created_date";
								$prime_cell_val   .= '"'.$this->logged_id.'",'.'"'.$created_on.'"';
								$prime_column_val  = rtrim($prime_column_val,",");
								$prime_cell_val    = rtrim($prime_cell_val,",");
								$prime_query       = "insert into $this->prime_table ($prime_column_val) VALUES ($prime_cell_val)";
								$insert_info   = $this->db->query("CALL sp_a_run ('INSERT','$prime_query')");
								$insert_result = $insert_info->result();
								$insert_info->next_result();
								$insert_id = $insert_result[0]->ins_id;
								
								$status_info['Status'] = "Inserted to DB";
							}else
							if((int)$exist_count === 1 && $picklist_sts){
								$trans_status = (int)$exist_result[0]->trans_status;
								$upd_prime_id = (int)$exist_result[0]->$prime_id;
								if($trans_status === 0){
									$upd_query = 'UPDATE '.$this->prime_table.' SET trans_updated_by = "'.$this->logged_id.'",trans_updated_date = "'.$created_on.'" , trans_status = 1 WHERE '.$prime_id.' = "'.$upd_prime_id.'"';
									$this->db->query("CALL sp_a_run ('RUN','$upd_query')");
									$status_info['status'] = "Changed to active";
								}else{
									$status_info['status'] = "Already Exist in DB";
								}							
							}else
							if($picklist_sts){
								$status_info['status'] = "Already Exist in DB";
							}
							$status_array[] = $status_info;
						}
					}
					$table_info = $this->get_excel_import_ui($status_array);
					return json_encode(array('success'=>true,'message'=>"Successfully file imported",'table_info'=>$table_info));
				}
			}
		}
	}
		
//LOAN IMPORT DATA AND VALIDATION PARTS START
	public function do_loan_excel_import($import_id){
		$filename = dirname(__FILE__)."/php_excel/PHPExcel/IOFactory.php";
		include($filename);
		if($import_id < 0){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}
		$excel_path_qry    = 'select * from cw_import where import_id = "'.$import_id.'"';
		$excel_path_info   = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
		$excel_path_result = $excel_path_info->result();
		$excel_path_info->next_result();
		if(!$excel_path_result){
			return json_encode(array('success' => false, 'message' => "Invalid file upload"));
		}else{
			$excel_file_path    = $excel_path_result[0]->excel_file_path;
			$module_id          = $excel_path_result[0]->module_id;
			$excel_format       = $excel_path_result[0]->excel_format;
			$excel_sheet_name   = (int)$excel_path_result[0]->excel_sheet_name;
			$excel_row_start    = (int)$excel_path_result[0]->excel_start_row;
			$excel_row_end      = (int)$excel_path_result[0]->excel_end_row;
			$format_qry 	    = 'select * from cw_util_excel_format where prime_excel_format_id = "'.$excel_format.'" and cw_util_excel_format.trans_status = 1';
			$format_info    = $this->db->query("CALL sp_a_run ('SELECT','$format_qry')");
			$format_rslt    = $format_info->result();
			$format_info->next_result();
			if(!$format_rslt){
				return json_encode(array('success' => false, 'message' => "Please add excel format before import"));
			}else{
				$exist_column_name = explode(",",$format_rslt[0]->exist_column_name);
				$excel_format_qry 	= 'select IFNULL(pick_list_import,0) as pick_list_import,view_name,duplicate_data,picklist_data,field_type,pick_table,pick_list_type,pick_list,mandatory_field,field_isdefault,excel_line_column_name,excel_line_value from cw_util_excel_format_line inner join cw_form_setting on label_name = excel_line_column_name where excel_line_module_id = "'.$module_id.'" and prime_excel_format_id = "'.$excel_format.'" and cw_form_setting.prime_module_id = "'.$module_id.'" and cw_util_excel_format_line.trans_status = 1';		
				$excel_format        = $this->db->query("CALL sp_a_run ('SELECT','$excel_format_qry')");
				$excel_format_result = $excel_format->result();
				$excel_format->next_result();
				if(!$excel_format_result){
					return json_encode(array('success' => false, 'message' => "Please map excel cell column before import"));
				}else{
					try{
						$excel_obj = PHPExcel_IOFactory::load($excel_file_path);
					}catch(Exception $e){
						die('Error loading file "' . pathinfo($excel_file_path, PATHINFO_BASENAME). '": ' . $e->getMessage());
						return json_encode(array('success' => false, 'message' => "Invalid file or path"));
					}
					$sheet           = $excel_obj->getSheet($excel_sheet_name);
					if($excel_row_end){
						$total_rows = $excel_row_end;
					}else{
						$total_rows = $sheet->getHighestRow();
					}
					
					//LOAN DATA VALIDATION MANDATORY FILED AND 
					$err_column_array    = array();
					$err_column_tabview  = array();
					foreach($excel_format_result as $excel_info){
						$mandatory_field         = (int)$excel_info->mandatory_field;
						$field_type              = (int)$excel_info->field_type;
						$excel_line_column_name  = $excel_info->excel_line_column_name;
						$excel_line_value        = $excel_info->excel_line_value;
						$view_name               = $excel_info->view_name;
						$pick_table              = $excel_info->pick_table;
						$pick_list_type          = (int)$excel_info->pick_list_type;
						$pick_list               = $excel_info->pick_list;
						$picklist_data           = (int)$excel_info->picklist_data;
						$pick_list_import        = (int)$excel_info->pick_list_import;
						
						$common_multi_cell_value = $sheet->rangeToArray("$excel_line_value$excel_row_start:$excel_line_value$total_rows", NULL, TRUE, TRUE, TRUE);
						$i = $excel_row_start;
						foreach($common_multi_cell_value as $common_value){
							foreach($common_value as $col_key =>$col_value){
								if(empty($col_value) && !is_numeric($col_value)){
									$err_column_array['error']["$excel_line_value$i"] = $view_name;
									$msg_line = "columns are empty and invalid data is present please check it?";
									$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
								}elseif((int)$field_type === 5 || (int)$field_type === 7){
									if($pick_list_import !== 1){
										if($pick_list_type === 1){
											$pick_list_val   = explode(",",$pick_list);
											$pick_list_val_1 = $pick_list_val[0];
											$pick_list_val_2 = $pick_list_val[1];
											$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$col_value.'"';
											$pick_data  = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
											$pick_result = $pick_data->result();
											$pick_count  = $pick_data->num_rows();
											$pick_data->next_result();
											if((int)$pick_count === 0){
												$err_column_array['error']["$excel_line_value$i"] = $view_name;
												$msg_line = "column invalid data is present please check it?";
												$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
											}
										}
									}
								}elseif($field_type === 4){
									$excel_date     = $sheet->getCell("$excel_line_value$i")->getValue();	
									$unix_date      = $this->unix_convertion($excel_date);
									if($unix_date <= 0){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
											$msg_line = "Please enter valid date... Please map The Date Format Like (DD/MM/YYYY)";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}	
								}elseif($excel_line_column_name === "employee_code"){
									$emp_code_qry = 'select count(*) as rslt_count from cw_employees where trans_status = 1 and employee_code = "'.$col_value.'"';
									$emp_data  = $this->db->query("CALL sp_a_run ('SELECT','$emp_code_qry')");
									$emp_data_result = $emp_data->result();
									$emp_data->next_result();
									$rslt_count = $emp_data_result[0]->rslt_count;
									if((int)$rslt_count === 0){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
										$msg_line = "employee code is not exit in employee master please check it?";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}
								}elseif($excel_line_column_name ==="loan_amount"){
									$col_value = str_replace(',', '', $col_value);
									if(!is_numeric($col_value)){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
										$msg_line = "column invalid data is present please check it?";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}
								}elseif($excel_line_column_name ==="interest_rate"){
									if(!is_numeric($col_value)){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
										$msg_line = "column invalid data is present please check it?";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}
								}elseif($excel_line_column_name ==="number_of_installment"){
									if(!is_numeric($col_value)){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
										$msg_line = "column invalid data is present please check it?";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}
								}elseif($excel_line_column_name ==="per_month"){
									$col_value = str_replace(',', '', $col_value);
									if(!is_numeric($col_value)){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
										$msg_line = "column invalid data is present please check it?";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}
								}elseif($excel_line_column_name ==="total_amount"){
									$col_value = str_replace(',', '', $col_value);
									if(!is_numeric($col_value)){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
										$msg_line = "column invalid data is present please check it?";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}
								}
								$i++;
							}
						}
					}
					$err_status_array	    = array();
					for($row = $excel_row_start; $row <= $total_rows; $row++) {
						foreach($excel_format_result as $excel_info){
							$field_type             = (int)$excel_info->field_type;
							$excel_line_column_name = $excel_info->excel_line_column_name;
							$excel_line_value       = $excel_info->excel_line_value;
							$view_name              = $excel_info->view_name;
							$get_cell_value         = trim($sheet->getCell("$excel_line_value$row")->getCalculatedValue());
							if($excel_line_column_name === "emp_code"){
								$emp_code   = $get_cell_value;
								$doj_date_qry = 'select date_of_joining from cw_employees where trans_status = 1 and employee_code = "'.$emp_code.'"';
								$doj_date_data  = $this->db->query("CALL sp_a_run ('SELECT','$doj_date_qry')");
								$doj_date_result = $doj_date_data->result();
								$doj_date_data->next_result();
								$doj_date = $doj_date_result[0]->date_of_joining;
								$doj_date = strtotime($doj_date);
								$emp_line_val   = $excel_info->excel_line_value;
								$emp_view_name  = $view_name;
								
							}
							if($excel_line_column_name === "loan_date"){
								$loan_date_val   = $get_cell_value;
								if(!empty($loan_date_val)){
									$loan_cell_value = trim(date('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getValue())));
									$loan_date = strtotime($loan_cell_value);
									$loan_line_val   = $excel_info->excel_line_value;
									$loan_view_name  = $view_name;
									$loan_date_value = trim(date('m-Y',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getValue())));
								}
							}
							if($excel_line_column_name === "apply_year"){
								$apply_date_val   = $get_cell_value;
								if(!empty($apply_date_val)){
									$apply_month_line_val   = $excel_info->excel_line_value;
									$apply_month_view_name  = $view_name;
									$apply_cell_value = trim(date('m-Y',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getValue())));
								}
							}
							if($excel_line_column_name === "category"){
								$category   = $get_cell_value;
								$cat_id_qry = 'select prime_category_id from cw_category where trans_status = 1 and category_name = "'.$category.'"';
								$cat_id_data  = $this->db->query("CALL sp_a_run ('SELECT','$cat_id_qry')");
								$cat_id_result = $cat_id_data->result();
								$cat_id_data->next_result();
								$cat_id        = $cat_id_result[0]->prime_category_id;
							}
							
							if($excel_line_column_name === "loan_amount"){
								$loan_amount         = $get_cell_value;
								$loan_amt_line_val   = $excel_info->excel_line_value;
								$loan_amt_view_name  = $view_name;
							}
							
							if($excel_line_column_name === "number_of_installment"){
								$no_of_install   = $get_cell_value;
							}
							
							if($excel_line_column_name === "per_month"){
								$per_month   = $get_cell_value;
							}

						}
						
						if($loan_date_value){
							$loan_date_qry = 'select count(*) as rslt_count from cw_transactions where trans_status = 1 and date_format(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y") , "%Y-%m") >= date_format(str_to_date(CONCAT("01-", "'.$loan_date_value.'"), "%d-%m-%Y") , "%Y-%m")';
							$loan_data  = $this->db->query("CALL sp_a_run ('SELECT','$loan_date_qry')");
							$loan_data_result = $loan_data->result();
							$loan_data->next_result();
							$loan_count = $loan_data_result[0]->rslt_count;
							if((int)$loan_count !== 0){
								$err_column_array['error']["$loan_line_val$row"] = $loan_view_name;
								$msg_line = "Payroll already processed this month, please check it?";
								$err_column_tabview['error']["$loan_line_val$row"]  = $loan_view_name." ".$msg_line;
								$err_status_array[] = "$excel_line_value$row";
							}
						}
						
						if($apply_cell_value){
							$apply_date_qry = 'select count(*) as rslt_count from cw_transactions where trans_status = 1 and date_format(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y") , "%Y-%m") >= date_format(str_to_date(CONCAT("01-", "'.$apply_cell_value.'"), "%d-%m-%Y") , "%Y-%m")';
							$apply_data  = $this->db->query("CALL sp_a_run ('SELECT','$apply_date_qry')");
							$apply_data_result = $apply_data->result();
							$apply_data->next_result();
							$apply_count = $apply_data_result[0]->rslt_count;
							if((int)$apply_count !== 0){
								$err_column_array['error']["$apply_month_line_val$row"] = $apply_month_view_name;
								$msg_line = "Payroll already processed this month, please check it?";
								$err_column_tabview['error']["$apply_month_line_val$row"]  = $apply_month_view_name." ".$msg_line;
								$err_status_array[] = "$excel_line_value$row";
							}
						}
						
						
						if($loan_date){
							if($loan_date < $doj_date){
								$err_column_array['error']["$loan_line_val$row"] = $loan_view_name;
								$msg_line = "loan date should not less than date of joining, please check it?";
								$err_column_tabview['error']["$loan_line_val$row"] = $msg_line;
								$err_status_array[] = "$excel_line_value$row";
							}
						}
						
						if($category && $emp_code){
							$emp_exit_qry = 'select count(*) as exit_count from cw_employees where trans_status = 1 and employee_code = "'.$emp_code.'" and role ="'.$cat_id.'"';
							$emp_exit_data  = $this->db->query("CALL sp_a_run ('SELECT','$emp_exit_qry')");
							$emp_exit_result = $emp_exit_data->result();
							$emp_exit_data->next_result();
							$emp_exit_count = $emp_exit_result[0]->exit_count;
							if((int)$emp_exit_count === 0){
								$err_column_array['error']["$emp_line_val$row"] = $emp_view_name;
								$msg_line = "Employee and category mismatched, please check it?";
								$err_column_tabview['error']["$emp_line_val$row"] = $msg_line;
								$err_status_array[] = "$excel_line_value$row";
							}
						}
						
						if($loan_amount && $no_of_install && $per_month){
							$tot_amount = 	$no_of_install * $per_month;
							if($tot_amount > $loan_amount){
								$err_column_array['error']["$loan_amt_line_val$row"] = $loan_amt_view_name;
								$msg_line = "Install amount is not greater than total amount, please check installment?";
								$err_column_tabview['error']["$loan_amt_line_val$row"] = $msg_line;
								$err_status_array[] = "$excel_line_value$row";
							}
						}
					}
					
					//LOAN DATA VALIDATION END
					$err_column_count = count($err_column_array['error']);
					$err_column       = implode(",",$err_column_array['error']);
					if((int)$err_column_count > 0) {
						$sts = true;
						$msg = "$err_column $msg_line";
						$table_info = $this->get_excel_error_ui($err_column_tabview);
						echo json_encode(array('success'=>false,'message'=>$msg,'table_info'=>$table_info));
						exit(0);
					}
					$status_array	    = array();
					$insert_sts	        = true;
					for($row =$excel_row_start; $row <= $total_rows; $row++) {
						$prime_column_val = "";
						$prime_cell_val   = "";
						$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;
							$excel_line_column_name = $excel_info->excel_line_column_name;
							$excel_line_value       = $excel_info->excel_line_value;
							$get_cell_value         = trim($sheet->getCell("$excel_line_value$row")->getCalculatedValue());
							if($field_type === 4){
								$get_cell_value = trim(date('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getValue())));
							}elseif($field_type === 5){
								$pick_list_val   = explode(",",$pick_list);
								$pick_list_val_1 = $pick_list_val[0];
								$pick_list_val_2 = $pick_list_val[1];
								$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
								$pick_data  = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
								$pick_result = $pick_data->result();
								$pick_count  = $pick_data->num_rows();
								$pick_data->next_result();
								$created_on  = date("Y-m-d H:i:s");
								if((int)$pick_count === 1){
									$pick_id     = $pick_result[0]->$pick_list_val_1;
									$pick_status = (int)$pick_result[0]->trans_status;
									$get_cell_value = $pick_id;
								}
							}elseif($excel_line_column_name === "apply_year"){
								$get_cell_value = trim(date('m-Y',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getValue())));
							}
							if($field_isdefault === 1){
								$get_cell_value    = str_replace("'",'^', $get_cell_value);
								$prime_column_val .= $excel_line_column_name.",";
								$prime_cell_val   .= "\'" . $get_cell_value . "\',";
								if(empty($exist_column_name)) {
									if($mandatory_field === 1){
										$exist_val .= $excel_line_column_name.' = "'.$get_cell_value.'" and ';
									}
								}else{
									if(in_array($excel_line_column_name,$exist_column_name)){
										/*if($excel_line_column_name === "apply_year"){
											$excel_line_col_name = "install_year";
										}else{*/
											$excel_line_col_name = $excel_line_column_name;
										/*}*/
										$exist_val .= $excel_line_col_name.' = "'.$get_cell_value.'" and ';
									}
								}
							}
							if(in_array("$excel_line_value$row", $err_status_array)){
								$insert_sts	        = false;
							}else{
								$insert_sts	        = true;
							}
						}
						if($prime_column_val){
							$prime_id    = "prime_".$module_id."_id";
							$exist_val   = rtrim($exist_val," and ");
							$exist_query = "select count(*) exist_count from cw_loan where trans_status =1 and $exist_val";
							$exist_info   = $this->db->query("CALL sp_a_run ('RUN','$exist_query')");
							$exist_result = $exist_info->result();
							$exist_info->next_result();
							$exist_count = $exist_result[0]->exist_count;
							$created_on  = date("Y-m-d h:i:s");
							if((int)$exist_count === 0){
								if($insert_sts){
									$prime_column_val .= "trans_created_by,trans_created_date";
									$prime_cell_val   .= '"'.$this->logged_id.'",'.'"'.$created_on.'"';
									$prime_column_val  = rtrim($prime_column_val,",");
									$prime_cell_val    = rtrim($prime_cell_val,",");
									$prime_query       = "insert into $this->prime_table ($prime_column_val) VALUES ($prime_cell_val)";
									$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'] = $err_column_tabview['error']["$emp_line_val$row"];
									$status_array[] = $status_info;
								}
							}else{
								$status_info['Status'] = "Already Exist in DB";
								$status_array[] = $status_info;
							}
						}
					}
					$table_info = $this->get_excel_import_ui($status_array);
					echo json_encode(array('success'=>true,'message'=>"Successfully datas are imported",'table_info'=>$table_info));
				}
			}
		}
	}
	
	public function get_excel_import_ui($status_array){
		$table_info = "";
		$th_line = "";
		$tr_line = "";		
		$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:#15da15 !important;'";
					$tr_line .= "<tr $color>$td_line</tr>";
					$td_line = "";
				}
			}
		}

		if($th_line !== ""){
			$table_info = "<table class='table table-bordered' style='text-align:center;' id='table_details'>
								<thead>
									<tr>
										$th_line
									</tr>
								</thead>
								<tbody>
									$tr_line
								</tbody>
						   </table>";
		}
		return $table_info;
	}

	//ERROR COLUMN AND ROW DISPLAY FOR INVALID DATAS
	public function get_excel_error_ui($err_column_tabview){
		$table_info = "";
		$th_line = "";
		$tr_line = "";
		foreach($err_column_tabview as $type => $err_column){
			$clr = 'green';
			if($type === 'error'){
				$clr = 'red';
			}
			foreach($err_column as $key => $value){
				$tr_line .= "<tr><td>$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){
	$filename = dirname(__FILE__)."/php_excel/PHPExcel/IOFactory.php";
	include($filename);
	if($import_id < 0){
		return json_encode(array('success' => false, 'message' => "Invalid file upload"));
	}		
	$excel_path_qry    = 'select * from cw_import where import_id = "'.$import_id.'"';
	$excel_path_info   = $this->db->query("CALL sp_a_run ('SELECT','$excel_path_qry')");
	$excel_path_result = $excel_path_info->result();
	$excel_path_info->next_result();
	if(!$excel_path_result){
		return json_encode(array('success' => false, 'message' => "Invalid file upload"));
	}else{
		$excel_file_path    = $excel_path_result[0]->excel_file_path;
		$module_id          = $excel_path_result[0]->module_id;
		$import_type        = $excel_path_result[0]->import_type;
		$excel_format       = $excel_path_result[0]->excel_format;
		$excel_sheet_name   = (int)$excel_path_result[0]->excel_sheet_name;
		$excel_row_start    = (int)$excel_path_result[0]->excel_start_row;
		$excel_row_end      = (int)$excel_path_result[0]->excel_end_row;
		$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,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 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 = PHPExcel_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();
				//Columnwise

				$columnwise_result   = $this->emp_excel_columnwise_checking($sheet,$excel_obj,$import_type,$excel_format_result,$excel_row_start,$total_rows,$module_id);
				
				$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{
						$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);
}

public function emp_excel_columnwise_checking($sheet,$excel_obj,$import_type,$excel_format_result,$excel_row_start,$total_rows,$module_id){
	$emp_code_qry         = 'select employee_code,termination_status from cw_employees where trans_status =1';
	$emp_code_data        = $this->db->query("CALL sp_a_run ('SELECT','$emp_code_qry')");
	$emp_code_data_result = $emp_code_data->result_array();
	$emp_code_data->next_result();
	$emp_code_data_result = array_map(function($v){
		$return_array     = array();
		$return_array['termination_status'] = $v['termination_status'];
		$return_array['employee_code']      = $v['employee_code'];
	    return $return_array;
	}, $emp_code_data_result);
	$emp_code_data_result = array_column($emp_code_data_result,'termination_status','employee_code');
	//GET A EMPLOYEE LEAVE STATUS 
	$leave_financial_info = $this->get_leave_financial_details();
	$prime_financial_id   = $leave_financial_info[0]->prime_leave_financial_year_id;
	$leave_status_query   = "SELECT employee_code from cw_request where cw_request.leave_status = 1 and cw_request.trans_status = 1 and financial_setting_id = '".$prime_financial_id."'";
	$leave_status_data    = $this->db->query($leave_status_query);
	$leave_status_result  = $leave_status_data->result_array();
	//BUILD A EMPLPOYEE LEAVE STATUS ARRAY
	$leave_status_result  = array_reduce($leave_status_result, function ($result, $arr) {
	    $result[$arr['employee_code']] = $arr;
	    return $result;
	}, array());
	//OVERTIME REQUEST
	$overtime_request_query   = "SELECT employee_code from cw_overtime_request where cw_overtime_request.approval_status = 1 and cw_overtime_request.trans_status = 1 and cw_overtime_request.financial_setting_id = '".$prime_financial_id."'";
	$overtime_request_data    = $this->db->query($overtime_request_query);
	$overtime_request_result  = $overtime_request_data->result_array();
	//BUILD A EMPLPOYEE LEAVE STATUS ARRAY
	$overtime_request_result  = array_reduce($overtime_request_result, function ($result, $arr) {
	    $result[$arr['employee_code']] = $arr;
	    return $result;
	}, array());
	//START CHECKING
	//DATA VALIDATION FOR MANDATORY FIELDS EMPTY OR INVALID DATA AND TAX RANGE ALSO CHECKED
	//GET UNIQUE FIELD
	$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());

	$array_uniq 		  = array();
	foreach($excel_format_result as $excel_info){
		$excel_line_value       = $excel_info->excel_line_value;
		$label_name             = $excel_info->label_name;
		$unique_field           = $excel_info->unique_field;
		$view_name              = $excel_info->view_name;
		if((int)$unique_field === 1){
			$array_uniq[$label_name]['view_name'] = $view_name;
			$array_uniq[$label_name]['label_name'] = $label_name;
		}
	}
	
	$uniq_result 	= array_diff_key($uniq_field_rslt,$array_uniq);

	//EXCEL MISSED UNIQUE COLUMN GET TO ERROR THROWING
	$employee_data_uniq   = array();
	$err_column_array     = array();
	$err_column_tabview   = array();
	$prime_id             = "prime_".$module_id."_id";
	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;
		}
	}
	
	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;
			$unique_field       	= (int)$excel_info->unique_field;
		//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
			//UNIQUE FIELD CHECK VALIDATION
			if((int)$unique_field === 1){
				$get_duplicat_value = array_map('array_filter', $multi_get_cell_value);//empty remove
				$get_duplicat_value = array_filter($get_duplicat_value);
				foreach($multi_get_cell_value as $key => $value) {
					$get_value      =  $value[$excel_line_value];
					if(!$employee_data_uniq[$label_name][$get_value]){
						$employee_data_uniq[$label_name][$get_value] = $excel_line_value;
					}else{
						$err_column_array['error']["$excel_line_value$key"] = $view_name;
						$msg_line   = "Duplicate Data Present in Excel Column, Please Check it?";
						$err_column_tabview['error']["$excel_line_value$key"]  = $view_name." ".$msg_line;
					}
				}
			}else
			if(($mandatory_field === 1) || ($picklist_data === 1)){
				$i = $excel_row_start;
				foreach($multi_get_cell_value as $arr_value){
					foreach($arr_value as $col_key =>$col_value){
						//DR CODE START FOR AADHAR CARD NO MANDETORY FIELD CHECK EXCEPT EXPAT CATEGORY 
						if($excel_line_column_name === "role"){
							$role   = $col_value;
						}
						if(empty($col_value) && !is_numeric($col_value)){
							if($excel_line_column_name === "aadhar_card_no" && $role !== "Expat"){
								$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;
							}else
							if($excel_line_column_name !== "aadhar_card_no"){
								$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;
							}		
						}else{
							if(($field_type === 5) || ($field_type === 7)){//picklist validation with data also validations
								if($pick_list_import !== 1){
									if($pick_list_type === 1){
										if($excel_line_column_name === "first_level_approval" || $excel_line_column_name === "second_level_approval" || $excel_line_column_name === "approve_type"){	
											if($leave_status_result[$employee_code]){
												$err_column_array['error']["$excel_line_value$i"] = $view_name;
												$msg_line = "Don't Change because our Request Status was Pending??";
												$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
											}else
											if($overtime_request_result[$employee_code]){
												$err_column_array['error']["$excel_line_value$i"] = $view_name;
												$msg_line = "Don't Change because our OT Request Status was Pending??";
												$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
											}else{
												$pick_list_val   = explode(",",$pick_list);
												$pick_list_val_1 = $pick_list_val[0];
												$pick_list_val_2 = $pick_list_val[1];
												$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$col_value.'"';								
												$pick_data  = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
												$pick_result = $pick_data->result();
												$pick_count  = $pick_data->num_rows();
												//echo "BSK $pick_query :: $pick_count <br/>";
												$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;
												}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 = "$col_value range not present please check it?";
															$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
														}
													}
												}
											}
										}else{
											$pick_list_val   = explode(",",$pick_list);
											$pick_list_val_1 = $pick_list_val[0];
											$pick_list_val_2 = $pick_list_val[1];
											$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$col_value.'"';
											$pick_data  = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
											$pick_result = $pick_data->result();
											$pick_count  = $pick_data->num_rows();
											$pick_data->next_result();
											if((int)$pick_count === 0){
												$err_column_array['error']["$excel_line_value$i"] = $view_name;
												$msg_line = "column invalid data is present please check it?";
												$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
											}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 = "$col_value range not present please check it?";
														$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 = "column invalid data is present please check it?";
												$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
											}
										}
									}
								}
							}elseif($field_type === 4){//date validations for mandatory field				
								$excel_date = trim(date('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell($col_key.$i)->getValue())));				
								if((int)$date_type === 1){
									if($excel_date === "1900-01-01"){
										$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($field_type === 1){
								if($excel_line_column_name === 'entry_time' || $excel_line_column_name === 'exit_time'){
									$value      = $col_value;
									$value      = explode(":", $value);					
									$hours      = (int)$value[0];
									$mins       = (int)substr("$value[1]",0,2);
									$meridiem   = substr("$value[1]",2,2);
									if(!(($hours >= 0 && $hours <= 12) && ($mins <= 60 && $mins >= 0) && ($meridiem === "AM" || $meridiem === "PM"))){
										if($excel_line_column_name === 'exit_time'){
											$err_column_array['error']["$excel_line_value$i"] = $view_name;
											$msg_line = "Invalid... Please map The Date Format Like (06:30AM)";
											$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... Please map The Date Format Like (09:30AM)";
											$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
										}
									}
								}
							}else 
							if($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 map The correct Email";
									$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
								}
							}else    
							if($field_type === 11){
								//FOR MOBILE NUMBER
								$length = strlen($col_value);
								$length_query = 'select field_length from cw_form_setting where cw_form_setting.prime_module_id = "'.$module_id.'" and label_name = "'.$excel_line_column_name.'"';
								$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){
									$err_column_array['error']["$excel_line_value$i"] = $view_name;
									$msg_line = "Invalid... Please map The correct mobile number";
									$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
								}
							}

							//amendment checking for duplicate data start
							if(((int)$import_type === 2) && ((int)$input_view_type !==3)){
								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 please check it?";
										$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;
									}
								}else
								if($excel_line_column_name === "first_level_approval" || $excel_line_column_name === "second_level_approval" || $excel_line_column_name === "approve_type"){
									if($leave_status_result[$employee_code]){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
										$msg_line = "Don't Change because our Request Status was Pending??";
										$err_column_tabview['error']["$excel_line_value$i"]  = $view_name." ".$msg_line;
									}else
									if($overtime_request_result[$employee_code]){
										$err_column_array['error']["$excel_line_value$i"] = $view_name;
										$msg_line = "Don't Change because our OT Request Status was Pending??";
										$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++;
					}
				}
			}
			elseif(($duplicate_data === 1) && ((int)$input_view_type !== 3)){//duplicate number validations for non-mandatory field
				$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) {
					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;
							}
						}
					}
				}
			}
		}	
	}
	//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){
	$permission_qry  = 'select role,count(*) as permission_count from cw_employee_permission where cw_employee_permission.trans_status = 1 group by role';
	$permission_info = $this->db->query("CALL sp_a_run ('SELECT','$permission_qry')");
	$permission_rslt = $permission_info->result_array();
	$permission_info->next_result();
	$permission_rslt = array_reduce($permission_rslt, function ($result, $arr) {
		$result[$arr['role']] = $arr['permission_count'];
		return $result;
	}, array());
	$this->save_info();
	$company_info   = $this->company_info();
	$minimum_age 	= $company_info[0]->minimum_age;
	$maximum_age 	= $company_info[0]->maximum_age;	
	$msg_line = "";
	$sts = 1;
	for($row = $excel_row_start; $row <= $total_rows; $row++) {
		$employee_code          = "";	
		$aadhar_card_no         = "";
		$label_name_arr         = array();
		foreach($excel_format_result as $excel_info){
			$field_type             = (int)$excel_info->field_type;
			$excel_line_column_name = $excel_info->excel_line_column_name;
			$excel_line_value       = $excel_info->excel_line_value;
			$view_name              = $excel_info->view_name;
			$pick_list_type         = (int)$excel_info->pick_list_type;
			$pick_list              = $excel_info->pick_list;
			$pick_table             = $excel_info->pick_table;
			$pick_list_import       = (int)$excel_info->pick_list_import;
			$mandatory_field        = (int)$excel_info->mandatory_field;
			$date_type              = (int)$excel_info->date_type;
			$get_cell_value         = trim($sheet->getCell("$excel_line_value$row")->getCalculatedValue());
			
			//UNIQUE VALIDATION PROCEDURE CHECK
			//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;
			}
			if($excel_line_column_name === "aadhar_card_no"){
				$aadhar_card_no            = $get_cell_value;
				// $post_data['aadhar_no']    = $get_cell_value;
			}

			if($excel_line_column_name === "bank_account_number"){
				if (preg_match('/[^a-zA-Z\d]/', $get_cell_value)) {
					$err_column_array['error']["$excel_line_value$row"] = $view_name;
					$msg_line = " Please check bank account number cell format....";
					$err_column_tabview['error']["$excel_line_value$row"]  = $get_cell_value." - ".$msg_line;
				}
			}			
			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('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
					}
					$str_dob        = strtotime($dob_date_value);
					if((int)$minimum_age > 0){
						$sminimum_age= "+$minimum_age";
					}
					if((int)$maximum_age > 0){
						$smaximum_age= "+$maximum_age";
					}
					$date_diff_val  = date( "Y-m-d", strtotime( "$dob_date_value $sminimum_age years" ));//after 14 years add
					$date_diff_val  = strtotime($date_diff_val);
					$date_max_val  = date( "Y-m-d", strtotime( "$dob_date_value $smaximum_age years" ));//after 14 years add
					$date_max_val  = strtotime($date_max_val);
					$dob_line_val   = $excel_info->excel_line_value;
					$dob_view_name  = $view_name;
				}
			}			
			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('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
				}
				$str_doj = strtotime($doj_date_value);
			}			
			if($excel_line_column_name === "family_date_of_birth"){
				$family_date = $get_cell_value;
				if(!empty($family_date)){
					$family_date_value = trim(date('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
					$str_family_date   = strtotime($family_date_value);
					$family_line_val   = $excel_info->excel_line_value;
					$family_view_name  = $view_name;
				}
			}			
			if($excel_line_column_name === "course_year_of_passing"){
				$course_date = $get_cell_value;
				if(!empty($course_date)){
					$course_date_value = trim(date('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
					$str_course_date   = strtotime($course_date_value);
					$course_line_val   = $excel_info->excel_line_value;
					$course_view_name  = $view_name;
				}
			}			
			if($excel_line_column_name === "training_date"){
				$training_date = $get_cell_value;
				if(!empty($training_date)){
					$training_date_value = trim(date('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
					$str_training_date   = strtotime($training_date_value);
					$training_line_val   = $excel_info->excel_line_value;
					$training_view_name  = $view_name;
				}
			}			
			if($excel_line_column_name === "previous_from_date"){
				$from_date = $get_cell_value;
				if(!empty($from_date)){
					$from_date_value = trim(date('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
					$str_from_date   = strtotime($from_date_value);
				}else{
					$today         = date('Y-m-d');
					$str_from_date = strtotime($today);
				}
				$from_date_line_val   = $excel_info->excel_line_value;
				$from_date_view_name  = $view_name;
			}			
			if($excel_line_column_name === "past_to_date"){
				$past_date = $get_cell_value;
				if(!empty($past_date)){
					$past_date_value = trim(date('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
					$str_past_date   = strtotime($past_date_value);
				}else{
					$today         = date('Y-m-d');
					$str_past_date = strtotime($today);
				}
				$past_date_line_val   = $excel_info->excel_line_value;
				$past_date_view_name  = $view_name;
			}
			if($excel_line_column_name === "resignation_date"){
				$resign_date_value = trim(date('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
				$str_resign = strtotime($resign_date_value);
				$resign_line_val   = $excel_info->excel_line_value;
				$resign_view_name  = $view_name;
			}
			if($excel_line_column_name === "last_working_date"){
				$last_work_date_value = trim(date('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
				$str_last_work_date        = strtotime($last_work_date_value);
				$last_work_date_val        = $excel_info->excel_line_value;
				$last_work_date_view_name  = $view_name;
			}else
			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('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getValue())));	
					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;
					}								
				}
			}
		}	
		//UNIQUE VALIDATION PROCEDURE CALL PROCESS 08DEC22 START	
		if($employee_code){
			// && $aadhar_card_no
			$post_json_data     = json_encode($post_data);				
			//function for validate a unique and mandatory field via mysql stored procedure
			$error_sts_arr      = $this->unique_procedure_valid($post_json_data);
			//PROCEDURE BASED UNIQUE VALIDATION ERROR
			if(count($error_sts_arr)){
				if($error_sts_arr[0] !== 1){
					$err_code       = $error_sts_arr[0]['employee_code'];
					$err_field      = $error_sts_arr[0]['field_name'];
					$err_value      = $error_sts_arr[0]['field_value'];
					$err_msg        = $error_sts_arr[0]['error_message'];
					$err_column_array['error']["$row"]    = $row;
					$err_view_name  = $label_name_arr[$err_field];
					$err_column_tabview['error']["$row"]  = "In $err_view_name($err_value) Already Exist for Employee Code($err_code).!";
				}
			}
		}
		//UNIQUE PROCEDURE VALIDATION PROCEDURE CALL PROCESS 08DEC22 END	
		$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
			if((int)$date_diff_val > (int)$str_doj){
				$err_column_array['error']["$dob_line_val$row"] = $dob_view_name;
				$msg_line = " and date of birth 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((int)$date_max_val < (int)$str_doj){
				$err_column_array['error']["$dob_line_val$row"] = $dob_view_name;
				$msg_line = " and date of birth minimum difference is $maximum_age years, please change the date?";
				$err_column_tabview['error']["$dob_line_val$row"]  = $dob_view_name." ". $msg_line; 
			}
		}
		
		if($str_family_date){//family details updated---29OCT2019
			if((int)$str_family_date > (int)$str_today){
				$err_column_array['error']["$family_line_val$row"] = $family_view_name;
				$msg_line = " not greater than today date, please change the date?";
				$err_column_tabview['error']["$family_line_val$row"]  = $family_view_name." ".$msg_line;
			}
		}
		
		if($str_course_date){//course year checking updated---30OCT2019
			$today     = date('Y-m-d');
			$str_today = strtotime($today);
			if((int)$str_course_date > (int)$str_today){
				$err_column_array['error']["$course_line_val$row"] = $course_view_name;
				$msg_line = " not greater than today date, please change the date?";
				$err_column_tabview['error']["$course_line_val$row"]  = $course_view_name." ". $msg_line;
			}
		}
		
		if($str_training_date){//Training date checking updated---30OCT2019
			$today     = date('Y-m-d');
			$str_today = strtotime($today);
			if((int)$sttraining_line_valr_training_date > (int)$str_today){
				$err_column_array['error']["$$row"] = $training_view_name;
				$msg_line = " is not greater than today date, please change the date?";
				$err_column_tabview['error']["$training_line_val$row"]  = $training_view_name." ".$msg_line;
			}
		}
		
		//experience start date and end date checking
		if($str_training_date){
			if((int)$str_from_date > (int)$str_today){
				$err_column_array['error']["$from_date_line_val$row"] = $from_date_view_name;
				$msg_line = " is not greater than today date, please change the date?";
				$err_column_tabview['error']["$from_date_line_val$row"]  = $from_date_view_name." ".$msg_line;
			}
		}
		
		if($str_past_date){
			if((int)$str_past_date > (int)$str_today){
				$err_column_array['error']["$past_date_line_val$row"] = $past_date_view_name;
				$msg_line = " is not greater than today date, please change the date?";
				$err_column_tabview['error']["$past_date_line_val$row"]  = $past_date_view_name." ".$msg_line;
			}
			if((int)$str_from_date >= (int)$str_past_date){
				$err_column_array['error']["$from_date_line_val$row"] = $from_date_view_name;
				$msg_line = " is not greater than to date, please change the date?";
				$err_column_tabview['error']["$from_date_line_val$row"]  = $from_date_view_name." ".$msg_line;
			}
		}
		
		if($str_resign){  //resgin date checking updated---17APR2020
			if((int)$str_resign > (int)$str_today){
				$err_column_array['error']["$resign_line_val$row"] = $resign_view_name;
				$msg_line = " not greater than today date, please change the date?";
				$err_column_tabview['error']["$resign_line_val$row"]  = $resign_view_name." ".$msg_line;
			}else
			if((int)$str_resign > (int)$str_last_work_date){
				$err_column_array['error']["$last_work_date_val$row"] = $last_work_date_view_name;
				$msg_line = " not lesser than Resign date, please change the date?";
				$err_column_tabview['error']["$last_work_date_val$row"]  = $last_work_date_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){
	$status_array	    = array();
	$formula_process    = array();
	for($row = $excel_row_start; $row <= $total_rows; $row++) {
		$prime_upd_query  = "";
		$prime_column_val = "";
		$prime_cell_val   = "";
		$exist_val        = "";
		$status_info = array();
		$status_info["Excel Row"] = $row;
		$sts = 1;
		foreach($excel_format_result as $excel_info){
			$field_isdefault        = (int)$excel_info->field_isdefault;
			$mandatory_field        = (int)$excel_info->mandatory_field;
			$field_type             = (int)$excel_info->field_type;
			$view_name              = $excel_info->view_name;
			$pick_table             = $excel_info->pick_table;
			$pick_list_type         = (int)$excel_info->pick_list_type;
			$pick_list_import       = (int)$excel_info->pick_list_import;
			$pick_list              = $excel_info->pick_list;
			$excel_line_column_name = $excel_info->excel_line_column_name;
			$excel_line_value       = $excel_info->excel_line_value;
			$input_view_type        = $excel_info->input_view_type;
			$date_type              = (int)$excel_info->date_type;
			$unique_field 			= (int)$excel_info->unique_field;
			// echo "unique_field ::$unique_field";
			$get_cell_value         = trim(iconv("UTF-8","ISO-8859-1",$sheet->getCell("$excel_line_value$row")->getCalculatedValue())," \t\n\r\0\x0B\xA0");
			if($field_type === 4){
			// FOR DATE			
				if((int)$date_type === 1){
					if($sheet->getCell("$excel_line_value$row")->getCalculatedValue()){
						$get_cell_value = trim(date('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
					}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(($field_type === 5) || ($field_type === 7) || ($field_type === 9)){
				if(($get_cell_value !='') || ($get_cell_value !=0)){ 
					if($pick_list_type === 1){
						$pick_list_val   = explode(",",$pick_list);
						$pick_list_val_1 = $pick_list_val[0];
						$pick_list_val_2 = $pick_list_val[1];
						if($pick_list_import === 1){
							$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_1.' = "'.$get_cell_value.'"';
						}else{
							$pick_query = 'select '.$pick_list.' from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
						}
						
						$pick_data  = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
						$pick_result = $pick_data->result();
						$pick_count  = $pick_data->num_rows();
						$pick_data->next_result();
						$created_on  = date("Y-m-d H:i:s");
						if((int)$sts != 0){
							if((int)$pick_count === 0){
								$pick_list_val_2 .= ",trans_created_by,trans_created_date";
								$get_cell_value_val = '"'.$get_cell_value.'",';
								$get_cell_value_val   .= '"'.$this->logged_id.'",'.'"'.$created_on.'"';
								if($pick_table !== $this->prime_table){
									$ins_query  = 'insert into '.$pick_table.'('.$pick_list_val_2.') VALUES ('.$get_cell_value_val.')';
									$ins_info   = $this->db->query("CALL sp_a_run ('INSERT','$ins_query')");
									$ins_result = $ins_info->result();
									$ins_info->next_result();
									$get_cell_value     = $ins_result[0]->ins_id;
									$second_insert_id   = $ins_result[0]->ins_id;
									$prime_id = $pick_table."_id";
									$prime_id = str_replace("cw_","prime_",$prime_id);
								}
							}else
							if((int)$pick_count > 0){
								//if($excel_line_column_name !== "designation"){
								if($pick_table !== $this->prime_table){
									$pick_id     = (int)$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;
									if($excel_line_column_name === "department"){
										$department_id = $pick_id;
										$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";
						if($pick_list_import === 1){
							$pick_query = 'select * from '.$pick_table.' where '.$pick_list_val_1.' = "'.$get_cell_value.'"';
						}else{
							$pick_query = 'select * from '.$pick_table.' where '.$pick_list_val_2.' = "'.$get_cell_value.'"';
						}
						$pick_data   = $this->db->query("CALL sp_a_run ('SELECT','$pick_query')");
						$pick_result = $pick_data->result();
						$pick_count  = $pick_data->num_rows();
						$pick_data->next_result();
						if((int)$pick_count === 0){
							if($pick_table !== $this->prime_table){
								$ins_query  = 'insert into '.$pick_table.'('.$pick_list_val_2.') VALUES ("'.$get_cell_value.'")';
								$ins_info   = $this->db->query("CALL sp_a_run ('INSERT','$ins_query')");
								$ins_result = $ins_info->result();
								$ins_info->next_result();
								$get_cell_value  = $ins_result[0]->ins_id;
							}
						}else
						if((int)$pick_count === 1){
							if($pick_table !== $this->prime_table){
								$pick_id     = (int)$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){
				$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 ';
					}
					$update_cell_val   = '"'.$get_cell_value.'",';
					$prime_upd_query   .= $excel_line_column_name."=".$update_cell_val;
				}else{
					if(in_array($excel_line_column_name,$exist_column_name)){
						$exist_val .= $this->prime_table .'.'.$excel_line_column_name.' = "'.$get_cell_value.'" and ';
					}
					$update_column_val = $excel_line_column_name;
					$update_cell_val   = '"'.$get_cell_value.'",';
					$prime_upd_query   .= $update_column_val."=".$update_cell_val;
				}
				
				//old application insert query building details start --18JAN2020
				if($excel_line_column_name === "employee_code"){
					$user_name = $get_cell_value;
					$code      = $get_cell_value;
				}
				if($excel_line_column_name === "date_of_joining"){
					$password = md5($get_cell_value);
					$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;
				}
				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;
				}
				//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     = array();
					if($user_right){
						$emp_permission_qry  = 'select * from cw_employee_permission where cw_employee_permission.trans_status =1 and cw_employee_permission.role = "'.$user_right.'"';
						$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_perm_grants_ary = array_reduce($emp_permission_rslt, function ($result, $arr) {
							$result[$arr['role']][] = $arr;
							return $result;
						}, array());
					}
					if((int)$import_type === 1){
						if((int)$exist_count === 0){
							$prime_column_val .= "user_name,password,trans_created_by,trans_created_date";
							$prime_cell_val   .= '"'.$user_name.'","'.$password.'","'.$this->logged_id.'",'.'"'.$created_on.'"';
							$prime_column_val  = rtrim($prime_column_val,",");
							$prime_cell_val    = rtrim($prime_cell_val,",");
							$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);
								$emp_data          = array("Compcode"=>"C0001","CODE"=>$code,"EMPNAME"=>$empname,"DEPT"=>$department,"DESIG"=>$designation,"DOJ"=>$doj,"DOB"=>$dob,"MARTIAL"=>$marital_status,"SEX"=>$gender,"cCode"=>$role);
								$imp_sts = False;
							}	
						}else{
							$imp_sts = True;
						}
					}else{
						if((int)$exist_count === 1){
							$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..";
							}
							
							$code_info   = $this->db->query("CALL sp_a_run ('SELECT','SELECT employee_code FROM `cw_employees` where prime_employees_id = ".$upd_prime_id." and trans_status = 1')");
							$code_result = $code_info->result();
							$code_info->next_result();
							$employee_code = $code_result[0]->employee_code;
						}else{
							$emp_code_qry    = 'select prime_employees_id from cw_employees where trans_status =1 and employee_code = "'.$code.'"';
							$emp_data        =  $this->db->query("CALL sp_a_run ('SELECT','$emp_code_qry')");
							$emp_data_result = $emp_data->result();
							$emp_data->next_result();
							$emp_id          = (int)$emp_data_result[0]->prime_employees_id;
							if($emp_id === 0){
								$status_info['Status'] = "Invalid Employee Code? Please Check it..!";
							}else{
								$imp_sts = True;
							}
						}
					}
				}
			}
			$status_array[] = $status_info;
		}
	}

	if($imp_sts){
		$table_info = "";
		$status     = False;
		$msg        = "Invalid Excel Format to Import";
	}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 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*/

//get notification details about fileds

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

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

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

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

	public function load_print_data($print_doc_id,$view_id){
		$data['print_sts'] = false;
		$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);
		$print_design         = str_replace("@today_date@",date("d-m-Y"),$print_design);
		$data['print_design'] = $print_design;
		return $data;
	}
	//NEHA EDIT END
	
	//number to words changed in payslip
	public function numbertowords($number){
		$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(){
		$file_path  = $this->input->post('file_path');
		$filename = dirname(__FILE__)."/php_excel/PHPExcel/IOFactory.php";
		include($filename);
		$excel_obj   = PHPExcel_IOFactory::load($file_path);
		$sheet_count = $excel_obj->getSheetCount();
		$sheet_name  = array();
		for($i= 0; $i< $sheet_count; $i++){
			$sheet        = $excel_obj->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.'"';
		$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;		
		$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_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($module_id,$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_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);
		require_once APPPATH."/controllers/php_excel/PHPExcel.php";
		$obj = new PHPExcel();		
		//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;
			$obj->getActiveSheet()->setCellValue($excel_line_value."1", $excel_line_column_name);
		}
		// Rename worksheet name
		 // $filename= $module_id.".xls"; //save our workbook as this file name
		 $filename= $excel_name.".xls"; //save our workbook as this file name
		 header('Content-Type: application/vnd.ms-excel'); //mime type
		 header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
		 header('Cache-Control: max-age=0'); //no cache
		 
		//save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
		 //if you want to save it as .XLSX Excel 2007 format
		 $objWriter = PHPExcel_IOFactory::createWriter($obj, 'Excel5');
		 //force user to download the Excel file without writing it to server's HD
		 $objWriter->save('php://output');
		echo json_encode(array('success' => TRUE, 'output' => $excelOutput));
	}
	//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;
		
		//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);*/
			//DR FUNCTION FOR MONTH DAY (MIN DATE AND MAX DATE GET FUNCTION) FROM 5JUL22
			$month_day_info        = $this->tos_day_info($employee_code,"3"); // 3 => Leave Entry
			if(count($month_day_info)){ 
				$salary_start_date    = $month_day_info['salary_start_date'];
				$salary_end_date      = $month_day_info['salary_end_date'];
				$year_end_date        = $month_day_info['year_end_date'];
				$starting_date        = $month_day_info['starting_date'];
				$ending_date          = $month_day_info['ending_date'];

				echo json_encode(array('success' => TRUE, 'category' => $category, 'date_of_joining' => $date_of_joining, 'department' => $department,  'first_level_approval' => $first_level_approval, 'second_level_approval' => $second_level_approval, 'component_value' => $component_value, '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){
		//GTE DEFAULT FINANCIAL YEAR
		$financial_info         = $this->get_leave_financial_details();
		$prime_financial_id     = $financial_info[0]->prime_leave_financial_year_id;	
		$starting_date          = date('Y-m-d',strtotime($financial_info[0]->starting_date));	
		$ending_date            = date('Y-m-d',strtotime($financial_info[0]->ending_date));	
		$month_day_result       = $this->month_day_qry_fun($category);
		if($month_day_result){
			$day_conditions    = $month_day_result[0]->day_conditions;
			$day_count         = $month_day_result[0]->day_count;
			$day_start         = "";
			$day_end           = "";
			$process_month     = "";
			$next_month        = "";

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

	       if(!$process_month){
	        	$process_month = date("m-Y",strtotime($starting_date));
				$day_start     = date('d',strtotime($starting_date));
				$day_end       = date('d',strtotime($ending_date));
	        }else{
	        	$next_month    = date('m-Y',strtotime("+1 month",strtotime("01-".$process_month)));
				if((int)$day_conditions === 3){
					//GET LAST DATE FOR CUTTOFF TYPE ONLY
					$day_start      = $month_day_result[0]->day_start;
					$day_end        = $month_day_result[0]->day_end;					
				}else{
					$day_start     = '01';
					$day_end       = date('t',strtotime("01-".$next_month));
				}
			}
			$today_date        = date('d-m-Y');
			$salary_end_year   = "12-".date('Y');
			if($day_conditions === "" || $day_start === "" || $day_end === ""){
				return false;
			}else{
				if((int)$day_conditions === 3){
					$sal_start         = $day_start;
					//For Current month between days increment
					$date              = new DateTime("01-$next_month 00:00:00");
					$date->modify('-1 month');
					$salary_start_date = $date->format("$sal_start-m-Y");	
					$salary_end_date   = date('d-m-Y',strtotime("$day_end-".$next_month));
					$year_end_date     = date("d-m-Y",strtotime($ending_date));
				}else{
					$sal_start         = $day_start;
					// $sal_start = '01';
					$date              = new DateTime("01-$next_month 00:00:00");
					$salary_start_date = $date->format("$sal_start-m-Y");	
					$salary_end_date   = date("d-m-Y",strtotime($day_end."-".$next_month));
					$year_end_date     = date("d-m-Y",strtotime($ending_date));
				}
				$month_day_arr      = array("salary_start_date" => $salary_start_date,"salary_end_date" => $salary_end_date,"year_end_date" => $year_end_date,"starting_date" => $starting_date,"ending_date" => $ending_date);
				return $month_day_arr;
			}
		}else{
			return false;
		}
	}
	//PROCESS MONTH WISE SALARY START DATE AND END DATE GET
	public function salary_start_end_info($category,$process_month){
		$month_day_result      = $this->month_day_qry_fun($category);
		if($month_day_result){
			$day_conditions    = $month_day_result[0]->day_conditions;
			$day_count         = $month_day_result[0]->day_count;
			$day_start         = $month_day_result[0]->day_start;
			$day_end           = $month_day_result[0]->day_end;
			
			if((int)$day_conditions === 3){
				$sal_start         = $day_start;
				//For Current month between days increment
				$date              = new DateTime("01-$process_month 00:00:00");
				$date->modify('-1 month');
				$salary_start_date = $date->format("$sal_start-m-Y");	
				$salary_end_date   = date('d-m-Y',strtotime("$day_end-".$process_month));
			}else{
				$sal_start         = '01';
				if((int)$day_conditions === 2){
					$day_end           = date('t',strtotime("01-".$process_month));
				}
				$date              = new DateTime("01-$process_month 00:00:00");
				$salary_start_date = $date->format("$sal_start-m-Y");	
				$salary_end_date   = date("d-m-Y",strtotime($day_end."-".$process_month));
			}
			$sal_start_end_arr     = array("salary_start_date" => $salary_start_date,"salary_end_date" => $salary_end_date);
			return $sal_start_end_arr;
		}
	}
	public function last_payroll_status($starting_date,$ending_date){
		$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
			$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));
			}
			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;
		$folder1    = $controller_name."_".$category_name;
		$pdf_name   = $emp_num;
		$final_html = $output;
		$oldmask = umask(0);
		if (!file_exists($folder)){
			mkdir($folder, 0777, true);
		}
		if (!file_exists($folder."/".$folder1)){
			mkdir($folder."/".$folder1, 0777, true);
		}
		//Check File Exist
		if(file_exists($folder."/".$folder1."/".$pdf_name.".pdf")){
			chmod($folder."/".$folder1."/".$pdf_name.".pdf", 0777);
			unlink($folder."/".$folder1."/".$pdf_name.".pdf");
		}
		file_put_contents($folder."/".$folder1."/".$pdf_name.".pdf" , $final_html);
		chmod($folder."/".$folder1."/".$pdf_name.".pdf", 0777);
		umask($oldmask);
		$path = $folder."/".$folder1."/".$pdf_name.".pdf";
		chmod($path, 0777, true);
		return $path;
	}
	
	//MRJ start 05OCT2020
	//formula column label name coloring
	public function coloring_label(){
		$formula_qry     = 'select * from cw_form_bind_input where input_cond_module_id = "'.$this->control_name.'" and trans_status = 1';
		$formula_data    = $this->db->query("CALL sp_a_run ('SELECT','$formula_qry')");
		$formula_result  = $formula_data->result();
		$formula_data->next_result();
		$this->formula_result = $formula_result;
	}
	
	public function role_based_condition(){
		$role_based_query  = 'select * from cw_role_base_condition where  role_module_id = "'.$this->control_name.'" and find_in_set("'.$this->logged_user_role.'",role_condition_for) and trans_status = 1';
		$role_based_info   = $this->db->query("CALL sp_a_run ('SELECT','$role_based_query')");
		$role_based_result = $role_based_info->result();
		$role_based_info->next_result();
		$role_based_condition = array();
		foreach($role_based_result as $key => $condition) {
			$role_based_condition[$condition->user_condition_type] = $condition->input_columns;
		}
		$this->role_based_condition = $role_based_condition;
	}
	public function trigger_sms($mobile_number,$sms_content,$template_id){
		//Get sms Configuration data
		$sms_config_query  = 'select sms_url,sms_sender_id,sms_username,sms_password,entityid from cw_company_information where trans_status = 1';
		$sms_config_info   = $this->db->query("CALL sp_a_run ('SELECT','$sms_config_query')");
		$sms_config_result = $sms_config_info->result();
		$sms_config_info->next_result();
		if($sms_config_result){
			$sms_url    = $sms_config_result[0]->sms_url;
			$sms_user   = $sms_config_result[0]->sms_username;
			$sms_pwd    = $sms_config_result[0]->sms_password;
			$sender_id  = $sms_config_result[0]->sms_sender_id;
			$entityid   = $sms_config_result[0]->entityid;
		}
		$url = "$sms_url?username=$sms_user&password=$sms_pwd&type=0&dlr=1&destination=$mobile_number&entityid=$entityid&source=$sender_id&message=".urlencode($sms_content)."&tempid=$template_id";
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		$output = curl_exec($ch);
		curl_close($ch);
		if($ch){
			return true;
		}		
	}
	public function load_sms_data($sms_design,$block_id,$view_id){
		$data['sms_sts'] 	= false;	
		$block_qry    		= 'select prime_sms_block_id,sms_block_column,sms_block_name,sms_block_table from cw_sms_block where sms_block_for = "'.$block_id.'" and trans_status = 1';
		$block_data   		= $this->db->query("CALL sp_a_run ('SELECT','$block_qry')");
		$block_result 		= $block_data->result();
		$block_data->next_result();
		$prime_sms_block_id  = $block_result[0]->prime_sms_block_id;
		$sms_block_column  	 = $block_result[0]->sms_block_column;
		$map_column			 = explode(",",$sms_block_column);

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

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

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

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

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

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

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

			if($mobile_list){
				$mobile_no 		= $pick_array[$mobile_no_column];
			}else{
				$employee_qry       = 'select employee_code,tl_report,manager_report,'.$mobile_no_column.' from cw_employees where cw_employees.employee_code = "'.$employee_column.'" and cw_employees.trans_status = 1';
				$employee_info      = $this->db->query("CALL sp_a_run ('SELECT','$employee_qry')");
				$employee_result    = $employee_info->result();
				$employee_info->next_result();
				$mobile_no 			= $employee_result[0]->$mobile_no_column;
			}
			if($mobile_no && $template_id && $sms_design){
				$sms_design    = $this->load_sms_data($sms_design,$block_id,$insert_id);
				$sms_content   = $sms_design['sms_design'];
				if($sms_content){
					$sms_rlst 	   = $this->trigger_sms($mobile_no,$sms_content,$template_id);
				}
				if($sms_rlst){
					$sms_status = 1;
					$sms_msg    = " and Sms Sent";
					$msg_rslt   = array('sms_status'=>$sms_status,'sms_msg'=>$sms_msg);
				}else{
					$sms_status = 0;
					$sms_msg    = " and Sms not Sent";
					$msg_rslt   = array('sms_status'=>$sms_status,'sms_msg'=>$sms_msg);
				}
				return $msg_rslt;
			}else{
				$sms_status = 0;
				$sms_msg    = "Mobile No or Tempate id or Sms Content Not Available";
				$msg_rslt   = array('sms_status'=>$sms_status,'sms_msg'=>$sms_msg);
				return $msg_rslt;
			}
		}else{
			$sms_status = 0;
			$sms_msg    = "Picklist Not changed";
			$msg_rslt   = array('sms_status'=>$sms_status,'sms_msg'=>$sms_msg);
			return $msg_rslt;
		}
	}
	
	public function send_mail_dynamic($mail_status_name,$get_to_mail,$config_result,$email_subject,$email_design,$bcc_mail,$attachment,$bcc_email_column){
		$smtp_server   = $config_result[0]->smtp_server;
		$sender_name   = $config_result[0]->sender_name;
		//$bcc           = explode(",",$config_result[0]->bcc);
		$port_no       = $config_result[0]->port_no;
		$sender_email  = $config_result[0]->sender_email;
		$username      = $config_result[0]->mail_username;
		$password      = $config_result[0]->mail_password;
		$conn_type     = $config_result[0]->connection_type;

		if($get_to_mail){
			try{
				$mail = new PHPMailer();
				// $mail->SMTPDebug = 1;
				$mail->IsSMTP();
				$mail->Host 	= $smtp_server; // Your SMTP PArameter
				$mail->Port 	= $port_no; // Your Outgoing Port
				$mail->SMTPAuth = true; // This Must Be True
				$mail->Username = $username; // Your Email Address
				$mail->Password = $password; // Your Password
				$mail->SMTPSecure = $conn_type; // Check Your Server's Connections for TLS or  SSL
				$mail->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;
		$style  = "<style>
		table{
			border: 1px !important;
			border-collapse: collapse !important;
			empty-cells: show !important;
			max-width: 100% !important;
			font-size: 13px !important;
		}
		tbody {
			border: 1px !important;
			border-collapse: collapse !important; 
			empty-cells: show !important;
			max-width: 100% !important;
			font-size: 13px !important;
		}
		td, th {
			border: 1px solid #000 !important;
			font-size: 13px !important;
		}
		td.fr-thick,th.fr-thick {
			border-width: 2px !important;
		}
		table.fr-dashed-borders td, table.fr-dashed-borders th {
			border-style: dashed !important;
		}
		</style>";
		$print_design  = $style."".$print_design;
		$print_design  = str_replace('~','"',$print_design);
		$block_qry    = 'select * from cw_print_block where print_block_for = "'.$email_design_for.'" and trans_status = 1';
		$block_data   = $this->db->query("CALL sp_a_run ('SELECT','$block_qry')");
		$block_result = $block_data->result();
		$block_data->next_result();
		foreach($block_result as $block){
			$prime_print_block_id  = $block->prime_print_block_id;
			$print_block_name      = $block->print_block_name;
			$print_block_type      = (int)$block->print_block_type;
			$print_block_table     = $block->print_block_table;
			$print_block_column    = $block->print_block_column;
			$suppressed_data       = $block->suppressed_data;
			$cumulative_data       = $block->cumulative_data;

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

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

						}else
						if($column == 'net_pay'){
							$value         = $rslt->$column;
							$print_design  = str_replace($replace_val,$value,$print_design);
							$net_pay_val   = $value;
							$net_pay_words = $this->numbertowords($net_pay_val);
							$net_pay_words = strtoupper($net_pay_words);
							$print_design  = str_replace("@net_pay_words@",$net_pay_words,$print_design);
						}else
						if($column == 'employee_name'){
							$value         = ucwords($rslt->$column);
							$print_design  = str_replace($replace_val,$value,$print_design);
						}else
						if($column == 'reporting_person'){
							$value         = ucwords($rslt->$column);
							$print_design  = str_replace($replace_val,$value,$print_design);
						}else
						if($column == 'salary'){
							$value         = $rslt->$column;
							$print_design  = str_replace($replace_val,$value,$print_design);
							$salary_val   = $value;
							$salary_words = $this->numbertowords($salary_val);
							$salary_words = ucwords($salary_words);
							$print_design  = str_replace("@salary_words@",$salary_words,$print_design);
						}
						
						if($split_array[$replace_val]){
							//Process split informtion 
							$process_function = $split_array[$replace_val];
							if((int)$process_function === 1){
								$transactions_month = $final_result[0]->transactions_month;
								$employee_code      = $final_result[0]->employee_code;
								$loan_info = $this->get_loan_value($transactions_month,$employee_code);
								$print_design = str_replace($replace_val,$loan_info,$print_design);
							}
						}else{
							if($print_block_type === 1){
								$print_design = str_replace($replace_val,$value,$print_design);
								foreach($assign_date_formate_list as $key=>$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;
	}
	public function send_email_notification($to_email,$first_to_email,$second_to_email,$bcc_mails,$email_subject,$body_content,$email_attachment){
		if($to_email){
			$config_query  = 'SELECT smtp_server,sender_name,bcc,port_no,sender_email,mail_username,mail_password 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->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;
				// print_r($mail);die;
				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((int)count($bcc_mails) > 0){
					foreach ($bcc_mails as $key => $mail_bcc){
						$mail->AddCC($mail_bcc);
					}
				}
				$mail->IsHTML(true);
				$mail->Subject = $email_subject;
				$mail->Body    = $body_content;
				//Attachment
				$folder = $email_attachment;
				if($folder){
					if(file_exists($folder)){
						$mail= $mail->Send();
						if($mail){
							$status = 1;
						}			
					}else{
						$status = 0;
					}
				}else{
					$mail= $mail->Send();
					if($mail){				
						$status = 1;
					}else{
						$status = 0;
					}
				}
			}catch(phpmailerException $e){
				$status = 0;
				$return_values = array('success'=>false,'message'=>"Mail Not Sent");
				return false;
			}catch(Exception $e){
				$status = 0;
				$return_values = array('success'=>false,'message'=>"Mail Not Sent");
				return false;
			}
			if($status){
				
				$return_values = array('success'=>true,'message'=>"Mail Successfully Sent");
				return $return_values;
			}else{
				$return_values = array('success'=>false,'message'=>"Mail Not Sent");
				return false;
			}
		}else{
			$return_values = array('success'=>false,'message'=>"Please Add Employee email id and Try Again!!");
			return $return_values;
		}
	}

	// PROVIDE TABLE VIEW
	public function get_table_info(){
		$table_query = 'select label_name,view_name,field_type from cw_form_setting  where prime_module_id = "'.$this->control_name.'" and input_view_type IN (1,2) and table_show = "1" ORDER BY table_sort asc';
	//and FIND_IN_SET("'.$this->logged_role.'",field_for) Removed for show all inputs
		$table_info = $this->db->query("CALL sp_a_run ('SELECT','$table_query')");
		$result   = $table_info->result();
		$table_info->next_result();
		$this->table_info = $result;
	}
	public function common_generate_pdf($table_data,$folder,$file_name,$set_paper,$paper_size,$pdf_set_password,$password){	
		// Load pdf library
		$pdf = new DOMPDF(array('enable_remote' => true,"enable_font_subsetting" => true));
		// Load HTML content 
		$pdf->loadHtml($table_data);
		// (Optional) Setup the paper size and orientation
		$pdf->setPaper($paper_size, $set_paper);
		// Render the HTML as PDF
		$pdf->render();
		define('DOMPDF_ENABLE_AUTOLOAD', false);
		if($pdf_set_password === "1"){
			//SET Production
			$pdf->get_canvas()->get_cpdf()->setEncryption($password, $password);
		}        
		// Output the generated PDF (1 = download and 0 = preview)
		$output 	= $pdf->output();
		$final_html = $output;
		$oldmask 	= umask(0);
		if (!file_exists($folder)){
			mkdir($folder, 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->company_info = $comp_result;
		return $comp_result;
	}
	//process month set for import process
	public function process_month_set(){
		$category              = $this->input->post('category');
		//GET DEFAULT FINANCIAL YEAR
		$financial_info        = $this->get_leave_financial_details();
		$prime_financial_id    = $financial_info[0]->prime_leave_financial_year_id;	
		$starting_date         = date('Y-m-d',strtotime($financial_info[0]->starting_date));	
		$ending_date           = date('Y-m-d',strtotime($financial_info[0]->ending_date));
		//GET A EMPLOYEE CODE AND PROCESS MONTH FORM LEAVE EXPORT MODULE
		$payroll_posting_query  = 'SELECT role as category,date_format(MAX(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y")) , "%m-%Y") AS process_month from cw_transactions where cw_transactions.role ="'.$category.'" and cw_transactions.trans_status = 1';			
		$payroll_posting_info   = $this->db->query("CALL sp_a_run ('SELECT','$payroll_posting_query')");
        $payroll_posting_result = $payroll_posting_info->result();
        $payroll_posting_info->next_result();
        $process_month          =  $payroll_posting_result[0]->process_month;
        if(!$process_month){
	    	$process_month = date("m-Y",strtotime($starting_date));
	    }else{
	    	$process_month = date("m-Y",strtotime("+1 month",strtotime("01-".$process_month)));
	    }
	    echo json_encode(array('process_month' =>$process_month));
	}
	//if we changes a shift request then we process a time entry 
	public function time_entry_process($employee_code,$shift_date,$shift_name){
		$time_entry_qry      = 'select COUNT(*) as time_entry_count from cw_time_entry where cw_time_entry.employee_code = "'.$employee_code.'" and cw_time_entry.att_date = "'.$shift_date.'" and cw_time_entry.trans_status = 1';
		$time_entry_info     = $this->db->query("CALL sp_a_run ('SELECT','$time_entry_qry')");
		$time_entry_result   = $time_entry_info->result();
		$time_entry_info->next_result();
		$time_entry_count    = (int)$time_entry_result[0]->time_entry_count;
		if($time_entry_count){
			$time_entry_run_info  = $this->db->query("CALL itsp_prcatt ('$shift_date','$shift_date','$employee_code')");
			$time_entry_run_rslt  = $time_entry_run_info->result();
			$time_entry_run_info->next_result();
			if($time_entry_run_rslt){
				return true;
			}else{
				return false;
			}
		}else{
			return true;
		}
	}
	//This Conditions Check for permission and manual punch and business trip
	public function check_exist_shift_sts($component_value,$employee_code,$shift_date){
		$leave_financial_info = $this->get_leave_financial_details();
		$financial_year_id    = $leave_financial_info[0]->prime_leave_financial_year_id;	

		$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){
		$leave_financial_info = $this->get_leave_financial_details();
		$financial_year_id    = $leave_financial_info[0]->prime_leave_financial_year_id;	
		//check exist from time entry 
		$time_entry_qry       = 'SELECT count(*) as count FROM cw_time_entry WHERE cw_time_entry.employee_code = "'.$employee_code.'" and cw_time_entry.att_date = "'.$shift_date.'" and cw_time_entry.trans_status = 1';
		$time_entry_info      = $this->db->query("CALL sp_a_run ('SELECT','$time_entry_qry')");
		$time_entry_rslt      = $time_entry_info->result();
		$time_entry_info->next_result();	
		$time_count           = (int)$time_entry_rslt[0]->count;

		//check exist from permission entry 
		$permission_entry_qry  = 'SELECT count(*) as count FROM cw_permission_entry WHERE cw_permission_entry.employee_code = "'.$employee_code.'" and cw_permission_entry.permission_date = "'.$shift_date.'" and cw_permission_entry.leave_status in (1,2) and financial_setting_id = "'.$financial_year_id.'" and trans_status = 1';
		$permission_entry_info = $this->db->query("CALL sp_a_run ('SELECT','$permission_entry_qry')");
		$permission_entry_rslt = $permission_entry_info->result();
		$permission_entry_info->next_result();	
		$permission_count      = (int)$permission_entry_rslt[0]->count;
		
		//check exist from manual punch entry 
		$man_punch_check_qry   = 'SELECT COUNT(*) as count from cw_manual_punch_entry where cw_manual_punch_entry.employee_code = "'.$employee_code.'" and cw_manual_punch_entry.shift_date = "'.$shift_date.'" and cw_manual_punch_entry.leave_status in (1,2) and financial_setting_id = "'.$financial_year_id.'" and trans_status = 1';
		$man_punch_check_info  = $this->db->query("CALL sp_a_run ('SELECT','$man_punch_check_qry')");
		$man_punch_check_rslt  = $man_punch_check_info->result();
		$man_punch_check_info->next_result();	
		$mp_check_count        = (int)$man_punch_check_rslt[0]->count;

		//check exist from overtime entry 
		$overtime_check_qry   = 'SELECT COUNT(*) as count from cw_overtime_entry where cw_overtime_entry.employee_code = "'.$employee_code.'" and cw_overtime_entry.entry_date = "'.$shift_date.'" and cw_overtime_entry.approval_status in (1,2) and financial_setting_id = "'.$financial_year_id.'" and trans_status = 1';
		$overtime_check_info  = $this->db->query("CALL sp_a_run ('SELECT','$overtime_check_qry')");
		$overtime_check_rslt  = $overtime_check_info->result();
		$overtime_check_info->next_result();	
		$overtime_count       = (int)$overtime_check_rslt[0]->count;
		if($permission_count || $mp_check_count || $overtime_count || $time_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_type){
		$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) && (int)$permission_type === 1){
				echo json_encode(array('success' => FALSE, 'message' => "You Have Reached Maximum Hours per Month?"));
				exit(0);
			}else
			if(($allow_per_day < $total_time) && (int)$permission_type === 1){
				echo json_encode(array('success' => FALSE, 'message' => "You Have Reached Maximum Hours per Day?"));
				exit(0);
			}else{
				//GTE DEFAULT FINANCIAL YEAR
				$financial_info  = $this->get_leave_financial_details();
				$prime_financial_id    = $financial_info[0]->prime_leave_financial_year_id;	
				$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
				//TIME OF SETTING BASED SALARY START AND END DATE DETAILS
				$month_day_info        = $this->leave_month_day($permission_date,$employee_code,"3"); // 3 => Leave Entry
				if(count($month_day_info)){
					$salary_start_date     = date("Y-m-d",strtotime($month_day_info["salary_start_date"]));
					$salary_end_date       = date("Y-m-d",strtotime($month_day_info["salary_end_date"]));
					$year_end_date         = date("Y-m-d",strtotime($month_day_info["year_end_date"]));

					$check_sts             = false;
					if($permission_date >= $salary_start_date && $permission_date <= $year_end_date){
						$check_sts         = true;
					}
					if($check_sts){
						$permission_entry_qry     = 'SELECT count(*) as count,SUM(total_minute) as total_time,employee_code,permission_date,shift_name FROM cw_permission_entry WHERE cw_permission_entry.employee_code = "'.$employee_code.'" and cw_permission_entry.permission_date >= "'.$salary_start_date.'" and cw_permission_entry.permission_date <= "'.$salary_end_date.'" and cw_permission_entry.leave_status in (1,2) and financial_setting_id = "'.$prime_financial_id.'" and trans_status = 1 and permission_type = "'.$permission_type.'" GROUP BY employee_code';
						$permission_entry_info    = $this->db->query("CALL sp_a_run ('SELECT','$permission_entry_qry')");
						$permission_entry_result  = $permission_entry_info->result();
						$permission_entry_info->next_result();	
						$permission_entry_count   = $permission_entry_result[0]->count;
						$month_permission_time    = $permission_entry_result[0]->total_time;
						
						if(((int)$permission_entry_count >= (int)$no_of_permissions) && (int)$permission_type === 1){
							echo json_encode(array('success' => FALSE, 'message' => "Already You Have Reached Number of Permission Limit per month?"));
							exit(0);
						}else{
							if($month_permission_time){
								$month_permission_time    = $month_permission_time + $total_time;
							}
							if(($month_permission_time >= $allow_per_month) && (int)$permission_type === 1){
								echo json_encode(array('success' => FALSE, 'message' => "Already You Have Reached Maximum Hours per Month?"));
								exit(0);
							}else{
								$day_permission_time       = "";
								$permission_allow_day_qry  = 'SELECT count(*) 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 and permission_type = "'.$permission_type.'" 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) && (int)$permission_type === 1){
									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 Already Processed for this Month...!"));
						exit(0);
					}
				}else{
					echo json_encode(array('success' => FALSE, 'message' => "Please Set Month Day for this Category..."));
					exit(0);
				}
			}
		}else{
			echo json_encode(array('success' => FALSE, 'message' => "Please 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){
				$in_time     = new DateTime($in_time);
		   		$out_time    = new DateTime($out_time);
		   		$timeDiff    = $in_time->diff($out_time);
		   		$days        = (int)$timeDiff->days;
		   		$total_time  = $timeDiff->format("%H:%I:%S");
			}else{
				$total_time  = "";
			}	
		}
		else{
			$in_date     = new DateTime($in_date." ".$in_time);
			$out_date    = new DateTime($out_date." ".$out_time);
			$timeDiff    = $in_date->diff($out_date);
			$days        = (int)$timeDiff->days;
			$total_time  = $timeDiff->format("%H:%I:%S");
		}
		if($total_time && ($days === 0 || $days === 1)){
			return $total_time;
		}else{
			return false;
		}
	}

	//function for get hours and minutes in two degits format
	public function hours_mins_cal($hrs_mins){
		$get_hrs            = floor($hrs_mins / 60);
		$get_mins           = ($hrs_mins -   floor($hrs_mins / 60) * 60);
		//ternary operator using for get a hour and minutes with two digits format
		$get_hrs_format     = (strlen((string)$get_hrs) === 1) ? ('0'.$get_hrs) : ($get_hrs);
		$get_mins_format    = (strlen((string)$get_mins) === 1) ? ('0'.$get_mins) : ($get_mins);
		
		$total_hrs_mins     = $get_hrs_format.':'.$get_mins_format;
		return $total_hrs_mins;
	} 
	//Convert Hour Format into mins
	public function hourstomins($hours){
		$timesplit=explode(':',$hours);
    	$min=($timesplit[0]*60)+($timesplit[1])+($timesplit[2]>30?1:0);
    	return $min;
	}
	//FOR MANUAL PUNCH VALIDATION
	public function manual_punch_shift(){
		$employee_code   = $this->input->post('employee_code');
		$day_type        = $this->input->post('day_type');
		$shift_date      = date("Y-m-d",strtotime($this->input->post('shift_date')));
		$shift_time_qry  = 'select cw_shift_import.shift_name,cw_shift_import.shift_date as shift_date,cw_shift_master.shift_status,cw_shift_master.in_time as import_in_time,cw_shift_master.out_time as import_out_time,cw_shift_master.from_time as from_time,cw_shift_master.to_time as to_time,cw_shift_master.first_half as first_half,cw_shift_master.second_half as second_half from cw_shift_import inner join cw_shift_master on cw_shift_master.prime_shift_master_id = cw_shift_import.shift_name where cw_shift_import.employee_code = "'.$employee_code.'" and cw_shift_import.shift_date = "'.$shift_date.'" and cw_shift_import.trans_status = 1';

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

		if($shift_time_result){
			echo json_encode(array('success' => TRUE, 'shift_result' => $shift_time_result));
		}else{
			echo json_encode(array('success' => FALSE, 'message' => "Shift not Allocated in this Date!"));
		}
	}

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

	
	//TIME ENTRY FUNCTION
	public function time_entry($post_data,$prime_financial_id,$leave_status){
		foreach ($post_data as $key => $value) {
			if($key === "employee_code"){
				$employee_code    = $value;
			}
			if($key === "prime_request_id"){
				$prime_request_id = $value;
			}
			if($key === "request_type"){
				$request_type     = (int)$value;
			}
			if($key === "leave_type"){
				$leave_type       = $value;
			}
			if($key === "from_date"){
				$from_date        = $value;
			}
			if($key === "from_date_type"){
				$from_date_type   = (int)$value;
			}
			if($key === "to_date"){
				$to_date          = $value;
			}
			if($key === "to_date_type"){
				$to_date_type     = (int)$value;
			}
			if($key === "shift_date"){
				$shift_date  = $value;
			}
			if($key === "in_date"){
				$in_date  = $value;
			}
			if($key === "out_date"){
				$out_date    = $value;
			}
			if($key === "in_time"){
				$in_time         = $value;
			}
			if($key === "out_time"){
				$out_time        = $value;
			}
			if($key === "day_type"){
				$shift_day_type  = (int)$value;
			}
		}
		//FOR MANUAL PUNCH
		if($request_type === 7){
			$from_date   = $shift_date;
			$to_date     = $shift_date;
		}
		//WE ADD A TIME WITH SECONDS BASED ON IN TIME AND OUT TIME LENGTH
		$in_time_count     = count(explode(":",$in_time));
		$out_time_count    = count(explode(":",$out_time));
		if((int)$in_time_count === 2){
			$in_time       = $in_time.":00";
		}
		if((int)$out_time_count === 2){
			$out_time      = $out_time.":00";
		}

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

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

		//SELECT EMPLOYEE DETAILS FROM EMPLOYEE MASTER BY DR (5JUL22)
		//get exist data from time log table
		$emp_detail_qry      = 'select role as category from cw_employees where cw_employees.employee_code = "'.$employee_code.'" and cw_employees.trans_status = 1';
		$emp_detail_info     = $this->db->query("CALL sp_a_run ('SELECT','$emp_detail_qry')");
		$emp_detail_result   = $emp_detail_info->result_array();
		$emp_detail_info->next_result();
		$category            = $emp_detail_result[0]['category'];

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

		$time_log_arr      = array_reduce($time_log_result, function($result, $arr){			
	    	$result[$arr['log_date']] = $arr;
	    	return $result;
		}, array());
		
		//SELECT QUERY FOR CHECK A EXISTS DATA FROM TIME ENTRY TABLE 
		$time_entry_qry      = 'select * from cw_time_entry where cw_time_entry.employee_code = "'.$employee_code.'" and cw_time_entry.att_date between ("'.$from_date.'") and ("'.$to_date.'") and cw_time_entry.trans_status = 1';
		$time_entry_info     = $this->db->query("CALL sp_a_run ('SELECT','$time_entry_qry')");
		$time_entry_result   = $time_entry_info->result_array();
		$time_entry_info->next_result();

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

		///QUERY FOR GET A SHIFT DATE AND IN AND OUT TIME FROM SHIFT AMSTER AND SHIFT IMPORT TABLES FOR MANUAL PUNCH REQUEST APPROVAL 
		$shift_time_qry     = 'select cw_shift_master.prime_shift_master_id,cw_shift_import.employee_code as employee_code,cw_shift_master.shift_name,cw_shift_import.shift_date as shift_date,cw_shift_import.from_date as from_date,cw_shift_master.from_time as from_time,cw_shift_import.to_date as to_date,cw_shift_master.to_time as to_time,cw_shift_master.first_half as first_half,cw_shift_master.second_half as second_half,cw_shift_master.shift_status as shift_status,(TRUNCATE(TIME_TO_SEC(cw_permission_setting.grace_time) / 60 ,2)) as grace_min,(TRUNCATE(TIME_TO_SEC(cw_permission_setting.late_hrs_max) / 60 ,2)) as late_max_min,excess_hours_allow,early_going_add_to_late as early_go_late from cw_shift_import inner join cw_shift_master on cw_shift_master.prime_shift_master_id = cw_shift_import.shift_name inner join cw_permission_setting on FIND_IN_SET(cw_shift_master.prime_shift_master_id, cw_permission_setting.shift_name) where cw_shift_import.employee_code = "'.$employee_code.'" and cw_shift_import.shift_date between ("'.$from_date.'") and ("'.$to_date.'") and FIND_IN_SET("'.$category.'", cw_permission_setting.component_value) and cw_shift_import.trans_status = 1';
		$shift_time_info   = $this->db->query("CALL sp_a_run ('SELECT','$shift_time_qry')");
		$shift_time_result = $shift_time_info->result_array();
		$shift_time_info->next_result();

		$shift_time_arr      = array_reduce($shift_time_result, function($result, $arr){			
	    	$result[$arr['shift_date']] = $arr;
	    	return $result;
		}, array());
		if($request_type === 7){
			if(!$shift_time_arr){
				echo json_encode(array('success' => false, 'message' => 'Shift Not Allocated in this Date'));
				exit(0);
			}
		}
		
		$status               = "true"; 
		$end_key              = end(array_keys($date_range));
		$time_entry_ins_value = "";
		$time_entry_upd_value = "";

		//GET LEAVE NAME INTERVENING TYPE AND INTERVENING HOLIDAYS FROM LEAVE CREATION TABLE
		$leave_creation_qry    = 'SELECT count(*) as creation_count,leave_opening,intervening_holidays,intervening_type,leave_description,leave_name from cw_leave_creation where cw_leave_creation.trans_status = 1 and prime_leave_creation_id = "'.$leave_type.'"';
		$leave_creation_info   = $this->db->query("CALL sp_a_run ('SELECT','$leave_creation_qry')");
		$leave_creation_result = $leave_creation_info->result();
		$leave_creation_info->next_result();
		$intervening_holidays  = $leave_creation_result[0]->intervening_holidays;
		$intervening_type      = explode(",",$leave_creation_result[0]->intervening_type);
		$leave_name  		   = $leave_creation_result[0]->leave_name;

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

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

		if($holiday_entry === 2){
			$holid_component_query  = 'SELECT label_name,components FROM cw_general_setting inner join cw_form_setting on cw_form_setting.prime_form_id = cw_general_setting.components WHERE entry_parameter_type = 2 and cw_general_setting.trans_status = 1';
			$holid_component_info   = $this->db->query("CALL sp_a_run ('SELECT','$holid_component_query')");
			$holid_component_result = $holid_component_info->result();
			$holid_component_info->next_result();	
		
			$holid_label_name    = $holid_component_result[0]->label_name;
			$emp_pick_arr        = $this->get_emp_data();
			$holid_comp_value    = $emp_pick_arr[$employee_code][$holid_label_name];

			$holiday_qry  = 'select cw_holiday_entry_holiday_data.holiday_date from cw_holiday_entry inner join cw_holiday_entry_holiday_data on cw_holiday_entry_holiday_data.prime_holiday_entry_id = cw_holiday_entry.prime_holiday_entry_id where FIND_IN_SET("'.$holid_comp_value.'", cw_holiday_entry_holiday_data.component_value) and cw_holiday_entry.holiday_year = "'.$get_year.'" and cw_holiday_entry.trans_status = 1 and cw_holiday_entry_holiday_data.trans_status = 1';
			$holiday_info   = $this->db->query("CALL sp_a_run ('SELECT','$holiday_qry')");
			$holiday_result    = $holiday_info->result_array();
			$holiday_info->next_result();		
			$holiday_result = array_reduce($holiday_result, function($result, $arr){			
			    $result[$arr['holiday_date']] = $arr;
			    return $result;
			}, array());
		}
		if($week_off_entry === 1){
			$check_weekoff_qry   = 'SELECT employee_code,weekoff_date,weekoff_type from cw_weekoff_import WHERE employee_code = "'. $employee_code .'" and weekoff_date >= (date_format(str_to_date("'.$from_date.'", "%d-%m-%Y") , "%Y-%m-%d")) and weekoff_date <= (date_format(str_to_date("'.$to_date.'", "%d-%m-%Y") , "%Y-%m-%d")) and financial_setting_id = '.$prime_financial_id.' and trans_status = 1';
			$check_weekoff_info   = $this->db->query("CALL sp_a_run ('SELECT','$check_weekoff_qry')");
			$check_weekoff_rlst   = $check_weekoff_info->result_array();
			$check_weekoff_info->next_result();

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

			/* Weekoff - START */
			$weekoff_qry = 'select cw_weekoff_entry_weekoff_days_details.weekday,cw_weekoff_entry_weekoff_days_details.first_week,cw_weekoff_entry_weekoff_days_details.second_week,cw_weekoff_entry_weekoff_days_details.third_week,cw_weekoff_entry_weekoff_days_details.fourth_week,cw_weekoff_entry_weekoff_days_details.fifth_week from cw_weekoff_entry inner join cw_weekoff_entry_weekoff_days_details on cw_weekoff_entry_weekoff_days_details.prime_weekoff_entry_id = cw_weekoff_entry.prime_weekoff_entry_id where FIND_IN_SET("'.$week_comp_value.'", cw_weekoff_entry.component_value) and cw_weekoff_entry.from_date <= (date_format(str_to_date("'.$from_date.'", "%d-%m-%Y") , "%Y-%m-%d")) AND cw_weekoff_entry.to_date >= (date_format(str_to_date("'.$to_date.'", "%d-%m-%Y") , "%Y-%m-%d")) and cw_weekoff_entry.trans_status = 1 and cw_weekoff_entry_weekoff_days_details.trans_status = 1';
			$weekoff_info   = $this->db->query("CALL sp_a_run ('SELECT','$weekoff_qry')");
			$weekoff_result    = $weekoff_info->result_array();
			$weekoff_info->next_result();
			$weekoff_result = array_reduce($weekoff_result, function($result, $arr){			
			    $result[$arr['weekday']] = $arr;
			    return $result;
			}, array());
			
			/* Weekoff - END */
			$days_arr = array("sun"=>1,"mon"=>2,"tue"=>3,"wed"=>4,"thu"=>5,"fri"=>6,"sat"=>7);
			$week_arr = array(1=>"first_week",2=>"second_week",3=>"third_week",4=>"fourth_week",5=>"fifth_week");
		}
		$msg     = "One or More Date(s) Already Exists in Attendance Entry";
		foreach ($date_range as $key => $common_date){
			$prime_time_id      = $time_entry_arr[$common_date]['prime_time_entry_id'];
			$punch_in           = $time_entry_arr[$common_date]['punch_in'];
			$punch_out          = $time_entry_arr[$common_date]['punch_out'];
			$manual_in          = $time_entry_arr[$common_date]['manual_in'];
			$manual_out         = $time_entry_arr[$common_date]['manual_out'];
			$late_in            = $time_entry_arr[$common_date]['late_in'];
			$early_out          = $time_entry_arr[$common_date]['early_out'];
			$early_in           = $time_entry_arr[$common_date]['early_in'];
			$excess_out         = $time_entry_arr[$common_date]['excess_out'];
			$total_work_hours   = $time_entry_arr[$common_date]['total_work_hours'];
			$total_late_hours   = $time_entry_arr[$common_date]['total_late_hours'];
			$total_excess_hours = $time_entry_arr[$common_date]['total_excess_hours'];
			$entry_flag         = $time_entry_arr[$common_date]['entry_flag'];
			$update_flag        = $time_entry_arr[$common_date]['update_flag'];
			$first_half_status  = $time_entry_arr[$common_date]['first_half_status'];
			$first_half_count   = $time_entry_arr[$common_date]['first_half_count'];
			$second_half_status = $time_entry_arr[$common_date]['second_half_status'];
			$second_half_count  = $time_entry_arr[$common_date]['second_half_count'];

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

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

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

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

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

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

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

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

						}else
						if((int)$weekoff_value === 2 && ($intervening_holidays !== 1 && !$get_common_holiday)){
							if($request_type === 1){
								$whole_day_status   = "SL";
								$second_half_status = $leave_name;
							}else
							if($request_type === 3 || $request_type === 8){
								$whole_day_status   = "SO";
								$second_half_status = "O";
							}
							$second_half_count  = 0.5;
							$ins_upd_rslt       = 1;
							
						}else{
							//IF LEAVE COUNT IS 0 SO NOT INSERT OR UPDATE TO TIME ENTRY
							$ins_upd_rslt = 0;
						}	
						if($request_type === 1){
							$entry_flag     = "L";
						}else
						if($request_type === 3 || $request_type === 8){
							$entry_flag     = "O";
						}
				
						//INSERT QUERY VALUE
						if($ins_upd_rslt){
							$time_entry_ins_value .= '("'.$employee_code.'","'.$shift_master_id.'","'.$common_date.'","'.$early_in.'","'.$late_in.'","'.$early_out.'","'.$excess_out.'","'.$total_work_hours.'","'.$total_late_hours.'","'.$total_excess_hours.'","'.$entry_flag.'","'.$update_flag.'","'.$whole_day_status.'","'.$from_date_time.'","'.$to_date_time.'","'.$first_half_status.'","'.$first_half_count.'","'.$second_half_status.'","'.$second_half_count.'","'.$this->logged_id.'","'.date("Y-m-d H:i:s").'"),';
						}
					}
				}
			}
		}

		if($status === "true"){
			$time_entry_upd_info      = "";
			$time_entry_ins_info      = "";
			if($this->control_name !== "request"){
				if($time_entry_upd_value){
					$time_entry_upd_value   = rtrim($time_entry_upd_value,",");
					//TIME ENTRY UPD QUERY
					$time_entry_upd_qry     = 'INSERT INTO cw_time_entry (prime_time_entry_id,shift_id,early_in,late_in,early_out,excess_out,total_work_hours,total_late_hours,total_excess_hours,entry_flag,update_flag,whole_day_status,manual_in,manual_out,first_half_status,first_half_count,second_half_status,second_half_count,trans_updated_by,trans_updated_date) VALUES '.$time_entry_upd_value.' ON DUPLICATE KEY UPDATE shift_id = VALUES(shift_id),early_in = VALUES(early_in),late_in = VALUES(late_in),early_out = VALUES(early_out),excess_out = VALUES(excess_out),total_work_hours = VALUES(total_work_hours),total_late_hours = VALUES(total_late_hours),total_excess_hours = VALUES(total_excess_hours),entry_flag = VALUES(entry_flag),update_flag = VALUES(update_flag),whole_day_status = VALUES(whole_day_status),manual_in = VALUES(manual_in),manual_out = VALUES(manual_out),first_half_status = VALUES(first_half_status),first_half_count = VALUES(first_half_count),second_half_status = VALUES(second_half_status),second_half_count = VALUES(second_half_count),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')");
				}
				if($time_entry_ins_value){
					$time_entry_ins_value   = rtrim($time_entry_ins_value,",");
					$time_entry_ins_qry     = 'INSERT INTO cw_time_entry (employee_code,shift_id,att_date,early_in,late_in,early_out,excess_out,total_work_hours,total_late_hours,total_excess_hours,entry_flag,update_flag,whole_day_status,manual_in,manual_out,first_half_status,first_half_count,second_half_status,second_half_count,trans_created_by,trans_created_date) VALUES '.$time_entry_ins_value.'';
					$time_entry_ins_info    = $this->db->query("CALL sp_a_run ('RUN','$time_entry_ins_qry')");
				}
				if($time_entry_upd_info || $time_entry_ins_info){
					return array('success' => "true", 'message' => 'proceed');
				}
			}else{
				return array('success' => "true", 'message' => 'proceed');
			}
		}else{
			return array('success' => "false", 'message' => $msg);
		}
	}
	
	//Get Last Payroll Month date
	public function get_last_payroll_month(){
		//GET A EMPLOYEE CODE AND PROCESS MONTH FORM LEAVE EXPORT MODULE
		$payroll_posting_query  = 'SELECT role as category,date_format(MAX(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y")) , "%m-%Y") AS process_month from cw_transactions where cw_transactions.role ="'.$category.'" and cw_transactions.trans_status = 1';			
		$payroll_posting_info   = $this->db->query("CALL sp_a_run ('SELECT','$payroll_posting_query')");
        $payroll_posting_result = $payroll_posting_info->result();
        $payroll_posting_info->next_result();
        $process_month          =  $payroll_posting_result[0]->process_month;
	}
	public function get_last_transaction($category){
		$payroll_query  = 'SELECT max(date_format(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y") , "%Y-%m")) as transactions_month FROM cw_transactions WHERE role = "'.$category.'" and trans_status =1 ORDER BY `prime_transactions_id` DESC';
		$payroll_info   = $this->db->query("CALL sp_a_run ('SELECT','$payroll_query')");
		$payroll_rslt   = $payroll_info->result();
		$payroll_info->next_result();
		$trans_last_month 	  = $payroll_rslt[0]->transactions_month;
		if($trans_last_month){
			$trans_last_month = $trans_last_month."-01";
			$trans_last_month = date('m-Y', strtotime('+1 month', strtotime($trans_last_month)));
		}
		return $trans_last_month;
	}
	public function get_category_name($role){
		$category_qry  	= 'select prime_category_id,category_name from cw_category where trans_status = 1 and prime_category_id in('.$role.')';
		$category_info  = $this->db->query("CALL sp_a_run ('SELECT','$category_qry')");
		$category_rslt  = $category_info->result_array();
		$category_info->next_result();
		$category_rslt 	= array_reduce($category_rslt, function ($result, $arr) {		
		    $result[$arr['prime_category_id']] = $arr['category_name'];
		    return $result;
		}, array());
		return $category_rslt;
	}
	public function where_month_value($module_name,$pdf_template,$process_month){
		$month_column_query  = 'select cw_print_block.month_column,cw_print_block.print_block_table from cw_print_info inner join cw_print_block on cw_print_block.print_block_for = cw_print_info.prime_print_info_id where print_info_module_id = "'.$module_name.'" and cw_print_info.trans_status = 1 and prime_print_info_id = "'.$pdf_template.'" and print_block_type = 1';
		$month_column_info   = $this->db->query("CALL sp_a_run ('SELECT','$month_column_query')");
		$month_column_rslt 	 = $month_column_info->result();
		$month_column_info->next_result();
		$where_month 		 = $month_column_rslt[0]->month_column;
		$where_table 		 = $month_column_rslt[0]->print_block_table;
		$module_name 		 = implode('","',explode(',', $where_table));
		$module_name 		 = str_replace('cw_', '', $module_name);
		$form_setting_qry  	 = 'select field_type,label_name,date_type from cw_form_setting where prime_module_id in ("'.$module_name.'") and cw_form_setting.trans_status = 1';
		$form_setting_info   = $this->db->query("CALL sp_a_run ('SELECT','$form_setting_qry')");
		$form_setting_rslt 	 = $form_setting_info->result_array();
		$form_setting_info->next_result();
		$form_setting_rslt   = array_reduce($form_setting_rslt, function($result, $arr){			
	    	$result[$arr['label_name']] = $arr;
	    	return $result;
		}, array());
		$where_month  = explode(',', $where_month);
		$where_column = "";
		foreach ($where_month as $key => $where_col) {
			$get_label_arr 	= explode('.', $where_col);
			$table_name 	= $get_label_arr[0];
			$label_name 	= $get_label_arr[1];
			$field_type 	= $form_setting_rslt[$label_name]['field_type'];
			$date_type    	= $form_setting_rslt[$label_name]['date_type'];
			if($label_name ==="transactions_month" && $table_name ==="cw_transactions"){
				$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\" ";
			}
		}
		return $where_column;
	}
	//BSK Get All Employees from excel sheet
	public function get_excel_employee_codes($sheet,$excel_row_start,$total_rows,$excel_format_result,$module_id){
		$employee_query  = 'select employee_code,termination_status,resignation_date from cw_employees where trans_status = 1';
		$employee_info   = $this->db->query("CALL sp_a_run ('SELECT','$employee_query')");
		$employee_rslt 	 = $employee_info->result_array();
		$employee_info->next_result();
		$employee_rslt 	 = array_reduce($employee_rslt, function($result, $arr){			
	    	$result[$arr['employee_code']] = $arr;
	    	return $result;
		}, array());

		$employee_codes_arr = array();
		for ($row = $excel_row_start; $row <= $total_rows; $row++){
			foreach($excel_format_result as $excel_info){
				$field_isdefault        = (int)$excel_info->field_isdefault;
				$mandatory_field        = (int)$excel_info->mandatory_field;
				$field_type             = (int)$excel_info->field_type;
				$pick_table             = $excel_info->pick_table;
				$pick_list_type         = (int)$excel_info->pick_list_type;
				$pick_list_import       = (int)$excel_info->pick_list_import;
				$pick_list              = $excel_info->pick_list;
				$excel_line_column_name = $excel_info->excel_line_column_name;
				$excel_line_value       = $excel_info->excel_line_value;
				if($excel_line_column_name === 'employee_code'){
					$get_cell_value         = ucwords(trim($sheet->getCell("$excel_line_value$row")->getValue()));
					$employee_codes_arr[] = $get_cell_value;
				}
				//resign employee array build
				$employee_status 	= $employee_rslt[$get_cell_value]['termination_status'];
				$resignation_date 	= $employee_rslt[$get_cell_value]['resignation_date'];
				if((int)$employee_status === 1){
					if($excel_line_column_name === 'from_date'){
						$from_date = trim(date('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
						$terminate_emp_arr[$row][$excel_line_column_name] 	= $from_date;
						$terminate_emp_arr[$row]['resignation_date'] 		= $resignation_date;
					}else
					if($excel_line_column_name === 'to_date'){
						$to_date = trim(date('Y-m-d',PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("$excel_line_value$row")->getCalculatedValue())));
						$terminate_emp_arr[$row][$excel_line_column_name] 	= $to_date;
						$terminate_emp_arr[$row]['resignation_date'] 		= $resignation_date;
					}
				}
			}
		}
		// resign employee error 
		foreach ($terminate_emp_arr as $row_key => $row_val) {
			$from_date 		= $row_val['from_date'];
			$to_date 		= $row_val['to_date'];
			$resign_date 	= $row_val['resignation_date'];
			if((strtotime($from_date) > strtotime($resign_date)) || (strtotime($to_date) > strtotime($resign_date))){
				$msg_line = "Employee Already Resigned...";
				$err_column_tabview['error']["$row_key"]  = $msg_line;
			}
		}
		$get_excel_employee_arr = array('employee_codes_arr'=>$employee_codes_arr,'err_column_tabview'=>$err_column_tabview);
		return $get_excel_employee_arr;
	}
	
	public function checkisprocessed($process_month,$where_query,$table_name){
		$exist_qry   = 'select count(*) as exist_count from '.$table_name.' where '.$table_name.'.trans_status =1 '.$where_query.' and process_month = "'.$process_month.'"';
        $exist_info  = $this->db->query("CALL sp_a_run ('SELECT','$exist_qry')");
        $exist_rslt  = $exist_info->result();
        $exist_info->next_result();
        $exist_count = $exist_rslt[0]->exist_count;
        return $exist_count;
	}
	public function excel_wkoff_exist_arr($sheet,$excel_row_start,$total_rows,$excel_format_result){
		$employee_codes_arr = array();	
		foreach($excel_format_result as $excel_info){
			$field_isdefault        = (int)$excel_info->field_isdefault;
			$mandatory_field        = (int)$excel_info->mandatory_field;
			$field_type             = (int)$excel_info->field_type;
			$pick_table             = $excel_info->pick_table;
			$pick_list_type         = (int)$excel_info->pick_list_type;
			$pick_list_import       = (int)$excel_info->pick_list_import;
			$pick_list              = $excel_info->pick_list;
			$excel_line_column_name = $excel_info->excel_line_column_name;
			$excel_line_value       = $excel_info->excel_line_value;
			$myDataArray[$excel_line_column_name] = $sheet->rangeToArray("$excel_line_value$excel_row_start:$excel_line_value$total_rows", NULL, True, True);

			$row_wise_arr 	= array();
			foreach ($myDataArray as $col_key => $value) {
				$i = $excel_row_start;
				foreach ($value as $row_key => $val) {
					$excel_data 	= $val[0];
					$row_wise_arr[$i][$col_key] 	= $excel_data;
					$i++;
				}
			}
		}	
		
		$date_build_arr = array();
		foreach ($row_wise_arr as $r_key => $row_value) {
			$f_date = str_replace('/', '-', $row_value['from_date']);
			$t_date = str_replace('/', '-', $row_value['to_date']);
			$from_date 	= date('Y-m-d',strtotime($f_date));
			$to_date 	= date('Y-m-d',strtotime($t_date));
			$emp_code 	= $row_value['employee_code'];
			$get_date 	= $this->getDatesFromRange($from_date, $to_date);
			$date_build_arr[$emp_code][$r_key]	= $get_date;
		}
		$err_column_tabview  = array();
		foreach ($date_build_arr as $emp_code => $row_value) {
			$date_arr  = array();
			foreach ($row_value as $row_key => $date_value) {
				foreach ($date_value as $date_key => $value) {
					if(in_array($value, $date_arr)){
						$msg_line = "Duplicate Date Exists. Please check your excel sheet";
						$err_column_tabview['error']["$row_key"]  = $msg_line;
					}else{
						$date_arr[]	= $value;
					}
				}
			}
		}
		return $err_column_tabview;
	}
	public function getDatesFromRange($start,$end,$format = 'Y-m-d') {
	    $array 			= array();
	    $array_error 	= array();
	    $interval 		= new DateInterval('P1D');
	    $realEnd 		= new DateTime($end);
	    $realEnd->add($interval);
	    $period 		= new DatePeriod(new DateTime($start), $interval, $realEnd);
	    foreach($period as $date) { 
	    	$check_date 	= $date->format($format);
	    	$date_build_arr = $date_build_arr[$r_key];
	    	if(in_array($check_date, $array)){
	    		$array_error[] = $date->format($format);
	    	}else{
	    		$array[] = $date->format($format);
	    	}
	    }
	    return $array;
	}
	
//--------------- DR CODE 5JUL22 FOR TIME OFFICE MIN DATE AND MAX DATE FUNCTION START---------------------------	
	//qry function for select a last payroll process month to compare for all category 
	public function last_pay_process_mon_info(){
		$last_pay_trans_qry  = 'SELECT role as category,date_format(MAX(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y")) , "%m-%Y") AS process_month from cw_transactions where cw_transactions.trans_status = 1';
		$last_pay_trans_info = $this->db->query("CALL sp_a_run ('SELECT','$last_pay_trans_qry')");
		$last_pay_trans_rslt = $last_pay_trans_info->result();
		$last_pay_trans_info->next_result();
		$process_month       = $last_pay_trans_rslt[0]->process_month;
		if(!$process_month){
			//IF NO ANY PAYROLL PROCESS MONTH GET CURRENT MONTH
			$process_month_obj   = (object)array('process_month' => date('m-Y'));
			$process_month_arr   = array(0 => $process_month_obj);
			return $process_month_arr;
		}else{
			return $last_pay_trans_rslt;
		}
	}
	
	//qry function for select a last payroll process month based on employee wise
	public function pay_process_mon_info($employee_code){
		$pay_posting_qry   = 'SELECT role as category,date_format(MAX(str_to_date(CONCAT("01-", transactions_month), "%d-%m-%Y")) , "%m-%Y") AS process_month from cw_transactions where cw_transactions.employee_code ="'.$employee_code.'" and cw_transactions.trans_status = 1';			
		$pay_posting_info  = $this->db->query("CALL sp_a_run ('SELECT','$pay_posting_qry')");
		$pay_posting_rslt  = $pay_posting_info->result();
		$pay_posting_info->next_result();
		$process_month     = $pay_posting_rslt[0]->process_month;
		if(!$process_month){
			//IF THIS EMPLOYEE WAS NEW JOINEE SO LAST PAYROLL MONTH GET
			return $this->last_pay_process_mon_info();
		}else{
			return $pay_posting_rslt;
		}
	}
	
	//TIME OFFICE SETTING BASED MONTH DAY QRY FUNCTION 
	public function tos_day_qry_fun($entry_parameter){
		$tos_mon_day_qry   = 'select day_conditions,day_count,day_start,day_end FROM cw_tos_month_day INNER JOIN cw_tos_parameter ON cw_tos_parameter.prime_tos_parameter_id = cw_tos_month_day.entry_parameter where cw_tos_parameter.trans_status = 1 and cw_tos_month_day.trans_status = 1 and cw_tos_parameter.prime_tos_parameter_id = "'.$entry_parameter.'"';
		$tos_mon_day_info  = $this->db->query("CALL sp_a_run ('SELECT','$tos_mon_day_qry')");
		$tos_mon_day_rslt  = $tos_mon_day_info->result();
		$tos_mon_day_info->next_result();
		return $tos_mon_day_rslt;
	}

	//TIME ENTRY POSTING MODULE MONTH DAY FUNCTION
	public function tos_posting_mon_day(){
		$entry_parameter     = $this->input->post('entry_parameter');
		$today_date          = date("Y-m-d");
		$today               = date("d");
		$financial_info      = $this->get_leave_financial_details();
		$prime_financial_id  = $financial_info[0]->prime_leave_financial_year_id;	
		$starting_date       = date('Y-m-d',strtotime($financial_info[0]->starting_date));	
		$ending_date         = date('Y-m-d',strtotime($financial_info[0]->ending_date));
		//TO CALL A TIME OFFICE SETTING BASED MONTH DAY QRY FUNCTION 
		$tos_mon_day_rslt    = $this->tos_day_qry_fun($entry_parameter);
		if($tos_mon_day_rslt[0]){
			$day_conditions      = (int)$tos_mon_day_rslt[0]->day_conditions;
			$day_count           = $tos_mon_day_rslt[0]->day_count;
			$day_start           = $tos_mon_day_rslt[0]->day_start;
			$day_end             = $tos_mon_day_rslt[0]->day_end;

			$pay_posting_result  = $this->last_pay_process_mon_info();

			$process_month       =  $pay_posting_result[0]->process_month;
			
			$month_day_arr       = $this->min_max_date_fun($prime_financial_id,$starting_date,$ending_date,$day_conditions,$day_count,$tos_mon_day_rslt,$process_month);

			$min_date            = $month_day_arr['salary_start_date'];
			$max_date            = $month_day_arr['salary_end_date'];
			$year_end_date       = $month_day_arr['year_end_date'];

			echo json_encode(array('success' => true, 'min_date' => $min_date, 'max_date' => $max_date, 'year_end_date' => $year_end_date));
		}else{
			echo json_encode(array('success' => false, 'message' => 'Please Set Min and Max Date for Process Time Entry..!Please Contact Admin..!'));
		}
	}

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

			$pay_posting_result  = $this->pay_process_mon_info($employee_code);

			$process_month       =  $pay_posting_result[0]->process_month;

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

		if(!$process_month){			
			$process_month = date("m-Y",strtotime($starting_date));
			$day_start     = date('d',strtotime($starting_date));
			$day_end       = date('d',strtotime($ending_date));
		}else{			
			if((int)$day_conditions === 3){
				//GET LAST DATE FOR CUTTOFF TYPE ONLY
				$day_start      = $month_day_result[0]->day_start;
				$day_end        = $month_day_result[0]->day_end;					
			}else{
				$day_start     = '01';
				$day_end       = date('t',strtotime("01-".$next_month));
			}
		}
		$next_month        = date('m-Y',strtotime("+1 month",strtotime("01-".$process_month)));
		$today_date        = date('d-m-Y');
		$salary_end_year   = "12-".date('Y');
		if($day_conditions === "" || $day_start === "" || $day_end === ""){
			return false;
		}else{
			if((int)$day_conditions === 3){
				$sal_start         = $day_start;
				//For Current month between days increment
				$date              = new DateTime("01-$next_month 00:00:00");
				$date->modify('-1 month');
				$salary_start_date = $date->format("$sal_start-m-Y");	
				$salary_end_date   = date('d-m-Y',strtotime("$day_end-".$next_month));
				$year_end_date     = date("d-m-Y",strtotime($ending_date));
			}else{
				$sal_start         = $day_start;
				$date              = new DateTime("01-$next_month 00:00:00");
				$salary_start_date = $date->format("$sal_start-m-Y");	
				$salary_end_date   = date("d-m-Y",strtotime($day_end."-".$next_month));
				$year_end_date     = date("d-m-Y",strtotime($ending_date));
			}
			$month_day_arr      = array("salary_start_date" => $salary_start_date,"salary_end_date" => $salary_end_date,"year_end_date" => $year_end_date,"starting_date" => $starting_date,"ending_date" => $ending_date);

			return $month_day_arr;
		}
	}

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

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

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

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

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

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

		//time office components count array build codes 
		$count_type_arr   =  array(""=>"---- Select Column----","P"=>"Present Count","A"=>"Absent Count","I"=>"Invalid Count","L"=>"Leave Count","H"=>"Holiday Count","W"=>"Weekoff Count","OD"=>"Onduty Count","M"=>"Manualpunch Count","excess_ot"=>"Excess Hours OT","shift_ot"=>"Shift OT","special_ot"=>"Special OT","total_ot"=>"Total Hours OT","paid_leave"=>"Paid Leave","paid_days"=>"Paid Days","weekoff_working"=>"WEEKOFF WORKING DAYS","weekoff_work_hours"=>"WEEKOFF WORKING HOURS","weekoff_work_mins"=>"WEEKOFF WORKING MINUTES","holiday_working"=>"HOLIDAY WORKING DAYS","holiday_work_hours"=>"HOLIDAY WORKING HOURS","holiday_work_mins"=>"HOLIDAY WORKING MINUTES","late_days"=>"LATE DAYS","late_hours"=>"LATE HOURS","late_mins"=>"LATE MINUTES","perm_days"=>"PERMISSION DAYS","perm_hours"=>"PERMISSION HOURS","perm_mins"=>"PERMISSION MINUTES","total_encash"=>"TOTAL ENCASH DAYS");

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

		$leave_name_arr    = array_reduce($leave_name_rslt, function ($result, $arr) {		
		    $result[$arr['leave_name']]          = $arr['leave_count'];
		    return $result;
		}, array());

 		$leave_opening_qry    = 'SELECT prime_leave_creation_id,leave_name,CONCAT("opening_", LOWER(leave_name) ) as leave_opening_name,CONCAT_WS(" Opening ",LOWER(leave_name)," count") as opening_count,CONCAT("encash_",LOWER(leave_name)) as leave_encash_name,CONCAT_WS(" Encash ",LOWER(leave_name)," count") as encash_count,CONCAT("balance_",LOWER(leave_name)) as balance_leave_name,CONCAT_WS(" Balance ",LOWER(leave_name), "count") as balance_count FROM cw_leave_creation WHERE trans_status = 1 and leave_opening = 1';
		$leave_opening_info   = $this->db->query("CALL sp_a_run ('SELECT','$leave_opening_qry')");
		$leave_opening_rslt   = $leave_opening_info->result_array();
		$leave_opening_info->next_result();

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

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

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

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

		//QUERY FOR GET A TIME ENTRY TABLE
		$time_qry 	   = 'SELECT permission_type,employee_code,att_date,cw_shift_master.shift_name,punch_in,punch_out,total_work_hours,total_late_hours,total_excess_hours,first_half_status,second_half_status,whole_day_status,total_permission,approved_ot_mins,approved_shift_ot,approved_special_ot,late_in,total_permission FROM cw_time_entry inner join cw_shift_master on cw_shift_master.prime_shift_master_id = cw_time_entry.shift_id where cw_time_entry.trans_status = 1 and att_date between "'.$start_date.'" and "'.$end_date.'"';

		$time_info     = $this->db->query("CALL sp_a_run ('SELECT','$time_qry')");
		$time_rslt 	   = $time_info->result_array();
		$time_info->next_result();

		$time_rslt     = array_reduce($time_rslt, function ($result, $arr) {		
		    $result[$arr['employee_code']][$arr['att_date']] = $arr;
		    return $result;
		}, array());
		//Get invalid punch
		$time_wrong_qry 	= 'SELECT employee_code,att_date,punch_in,punch_out,record_type FROM cw_time_wrong_entry where cw_time_wrong_entry.trans_status = 1 and att_date between "'.$start_date.'" and "'.$end_date.'"';
		$time_wrong_info   = $this->db->query("CALL sp_a_run ('SELECT','$time_wrong_qry')");
		$time_wrong_rslt 	= $time_wrong_info->result_array();
		$time_wrong_info->next_result();

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

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

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

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

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

		$week_off_entry        = (int)$param_based_type_arr['Weekly off Entry'];	
		$holiday_entry         = (int)$param_based_type_arr['Holiday Entry'];	
		$leave_entry           = (int)$param_based_type_arr['Leave Entry'];	

		if($holiday_entry === 2){
			//QUERY FOR GET A EMPLOYEE PICKLIST COMPOENENT DETAILS 
			$holid_component_query  = 'SELECT pick_table,pick_list,components,label_name FROM cw_general_setting inner join cw_form_setting on cw_form_setting.prime_form_id = cw_general_setting.components WHERE entry_parameter_type = 2 and cw_general_setting.trans_status = 1';
			$holid_component_info   = $this->db->query("CALL sp_a_run ('SELECT','$holid_component_query')");
			$holid_component_result = $holid_component_info->result();
			$holid_component_info->next_result();	
		
			$holid_pick_list   = $holid_component_result[0]->pick_list;
			$holid_label_name      = $holid_component_result[0]->label_name;

			//QUERY FOR GET A HOLIDAY ENTRY TABLE
			$holiday_qry   = 'SELECT holiday_date,component_value FROM cw_holiday_entry inner join cw_holiday_entry_holiday_data on cw_holiday_entry_holiday_data.prime_holiday_entry_id = cw_holiday_entry.prime_holiday_entry_id where cw_holiday_entry_holiday_data.trans_status = 1 and holiday_date between "'.$start_date.'" and "'.$end_date.'"';
			$holiday_info  = $this->db->query("CALL sp_a_run ('SELECT','$holiday_qry')");
			$holiday_rslt  = $holiday_info->result_array();
			$holiday_info->next_result();

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

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

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

		//QUERY FOR GET A LEAVE NAME COUNT FROM LEAVE ENTRY TABLE
		$leave_name_count_qry   = 'SELECT employee_code,leave_date,LOWER(cw_leave_creation.leave_name) as leave_name,SUM(leave_count) as leave_count,cw_leave_creation.paid_leave FROM cw_leave_entry inner join cw_leave_creation on cw_leave_creation.prime_leave_creation_id = cw_leave_entry.leave_type where cw_leave_entry.trans_status = 1 and cw_leave_creation.trans_status = 1 and cw_leave_entry.leave_date between "'.$start_date.'" and "'.$end_date.'" and cw_leave_entry.leave_status = 2 GROUP BY employee_code,cw_leave_creation.leave_name';
		$leave_name_count_info  = $this->db->query("CALL sp_a_run ('SELECT','$leave_name_count_qry')");
		$leave_name_count_rslt  = $leave_name_count_info->result_array();
		$leave_name_count_info->next_result();
		
		$leave_name_count_rslt  = array_reduce($leave_name_count_rslt, function ($result, $arr) {		
		    $result[$arr['employee_code']][$arr['leave_name']] = $arr;
		    return $result;
		}, array());
		$prime_table_query = 'SELECT leave_name FROM cw_leave_creation WHERE trans_status = 1 and leave_opening = 1';
		$columns_info      = $this->db->query("CALL sp_a_run ('SELECT','$prime_table_query')");
		$columns           = $columns_info->result();
		$columns_info->next_result();
		$select_columns    = "";
		foreach ($columns as $key => $value){
			$leave_name    =  strtolower($value->leave_name);
			if($leave_name){
				$select_columns  .= " encash_".$leave_name."+";
				//calculate leave balance
                $credit_columns  .= '(('.$leave_name."+".$leave_name.'_credit)-('.$leave_name.'_debit + used_'.$leave_name.'+ pending_'.$leave_name.'+ cw_leave_opening.encash_'.$leave_name.')) as balance_'.$leave_name.',';
                $opening_columns .='('.$leave_name."+".$leave_name.'_credit) as opening_'.$leave_name.',';
                                                           
			}			
		}
		$select_columns       = rtrim($select_columns,"+");
		$credit_columns       = rtrim($credit_columns,",");
		$opening_columns      = rtrim($opening_columns,",");
		//Encash data result
		$leave_encash_count_qry   = 'SELECT *,SUM('.$select_columns.') as total_encash FROM cw_leave_encash_days where cw_leave_encash_days.trans_status = 1 and cw_leave_encash_days.process_month = "'.$process_month.'" GROUP BY cw_leave_encash_days.employee_code';
		$leave_encash_count_info  = $this->db->query("CALL sp_a_run ('SELECT','$leave_encash_count_qry')");
		$leave_encash_count_rslt  = $leave_encash_count_info->result_array();
		$leave_encash_count_info->next_result();

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

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

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

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

			//Date between from and to date			
			foreach ($date_period as $key => $value){
			    $att_day                = $value->format('d');      
			    $att_date               = $value->format('Y-m-d');
			    $dis_date               = $value->format('d-m-Y');
			    //FOR HOLIDAY CHECK BASED ON GENERAL SETTING CHOSSED COMPONENT WISE
			    $emp_comp_value         = $emp_picklist_arr[$employee_code][$holid_label_name];
			   	$holiday_comp_value_arr = explode(",", $holiday_rslt[$att_date]);
			   	$first_half_status      = "-";
			    $second_half_status     = "-";
			  	//DAY STATUS AND STATUS BASED COUNT ADD START FROM DAY TO DAY WITH FORLOOP			    
			  	if($emp_act_sts === "In Active" && date("Y-m-d",strtotime($emp_resign_date)) < $att_date){
			  		$whole_day_status       = "";
			  		$whole_day_status_val  	= "-";
			  	}else
			  	if($emp_doj > $att_date){
			  		$whole_day_status       = "";
			  		$whole_day_status_val  	= "-";
			  	}else
			    if($time_rslt[$employee_code][$att_date]['whole_day_status']){
			    	$whole_day_status      = $time_rslt[$employee_code][$att_date]['whole_day_status'];
			    	$total_work_hours      = $time_rslt[$employee_code][$att_date]['total_work_hours'];
			    	$whole_day_status_val  = $day_status_rslt[$whole_day_status];
			    	$first_half_status     = $time_rslt[$employee_code][$att_date]['first_half_status'];
			    	$second_half_status    = $time_rslt[$employee_code][$att_date]['second_half_status'];
			    	$shift_name            = $time_rslt[$employee_code][$att_date]['shift_name'];
			    	$permission_type       = (int)$time_rslt[$employee_code][$att_date]['permission_type'];

					//EXCESS HOURS OT AND SHIFT OT COUNT
					$approved_ot_mins      = (int)$time_rslt[$employee_code][$att_date]['approved_ot_mins'];
					$approved_shift_ot     = (int)$time_rslt[$employee_code][$att_date]['approved_shift_ot'];
					$approved_special_ot   = (int)$time_rslt[$employee_code][$att_date]['approved_special_ot'];
					$late_in               = (int)$time_rslt[$employee_code][$att_date]['late_in'];
					$permission            = (int)$time_rslt[$employee_code][$att_date]['total_permission'];
			    	if($approved_ot_mins){
						$excess_ot_mins    = $excess_ot_mins + $approved_ot_mins;						
					}
					if($approved_shift_ot){
						$shift_ot_mins     = $shift_ot_mins + $approved_shift_ot;
					}
					if($approved_special_ot){
						$special_ot_mins   = $special_ot_mins + $approved_special_ot;
					}
					if($approved_ot_mins || $shift_ot_mins || $special_ot_mins){
						$total_ot_mins     = $excess_ot_mins + $shift_ot_mins + $special_ot_mins;
					}
					if($late_in > 0){
						$late_count           = $late_count + 1;						
						$late_mins            = $late_mins + $late_in;
			
					}
					if($permission_type === 1){
						$permission_count     = $permission_count + 1;						
						$permission_mins      = $permission_mins  + $permission;
					}
			    	if($present_arr[$whole_day_status]){
			    		$present_count      = $present_count + $present_arr[$whole_day_status];
			    		$present_shift[$employee_code][$shift_name] += $present_arr[$whole_day_status];
			    		if($first_half_status === "FP" && $second_half_status === "SP"){
			    			$first_half_status   = "P";
			    			$second_half_status  = "P";
			    		}
			    		if($first_half_status === "FHL" && $second_half_status === "SHL"){
			    			$absend_count       = $absend_count + 1;
			    		}else
			    		if($first_half_status === "FHL"){	
			    			$absend_count       = $absend_count + 0.5;
			    		}else
			    		if($second_half_status === "SHL"){
			    			$absend_count       = $absend_count + 0.5;
			    		}
			    	}
			    	if($leave_arr[$whole_day_status]){
			    		$leave_count        = $leave_count + $leave_arr[$whole_day_status];
			    	}
			    	if($onduty_arr[$whole_day_status]){
			    		$onduty_count       = $onduty_count + $onduty_arr[$whole_day_status];
			    	}
			    	if($mpunch_arr[$whole_day_status]){
			    		$mpunch_count       = $mpunch_count + $mpunch_arr[$whole_day_status];
			    	}
			    	if($unpunch_arr[$whole_day_status]){
			    		$absend_count       = $absend_count + $unpunch_arr[$whole_day_status];
			    		if($unpunch_arr[$whole_day_status] === "U"){
			    			$first_half_status  = "A";
				    		$second_half_status = "A";
				    		$whole_day_status   = "A";
			    		} 
			    	}
			    	if($invalid_arr[$whole_day_status]){
			    		$invalid_count   = $invalid_count + $invalid_arr[$whole_day_status];
			    	}
			    	if($whole_day_status === "H"){
			    		$holiday_count          = $holiday_count + 1; 	
			    	}
			    	if($whole_day_status === "H" && (int)$total_work_hours > 0){
			    		$holiday_work_count       = $holiday_work_count + 1; 	
			    		$holiday_work_mins        = $holiday_work_mins + $total_work_hours; 	
			    	}
			    	if($whole_day_status === "W" && (int)$total_work_hours > 0){
			    		$woff_work_count          = $woff_work_count + 1;
			    		$woff_work_mins           = $woff_work_mins + $total_work_hours;
			    	}
			    	if($weekoff_arr[$whole_day_status]){			    		
			    		$woff_count             = $woff_count + $weekoff_arr[$whole_day_status];
			    	} 
			    }else
			    if($time_wrong_rslt[$employee_code][$att_date]['record_type']){
			    	$whole_day_status_val   = "IP";
			    	$absend_count           = $absend_count + 1;
			    	$first_half_status      = "IP";
			    	$second_half_status     = "IP";
			    }else{
			    	$whole_day_status_val  	= "-";
			    }
			    
			    if($first_half_status === "U"){
			    	$first_half_status = "A";
			    }
			    if($second_half_status === "U"){
			    	$second_half_status = "A";
			    }

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

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

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

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

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

	/*THIS FUNCTION ADD BY ANDREWS*/
		//Coff Validation common for Overtime request and approval
	public function compoff_validation($employee_code,$category,$approved_over_time,$ot_type){
		$company_info       = $this->company_info();
		$coff_based_on      = $company_info[0]->coff_based_on; //Get from company info module.
		if(!$coff_based_on){
			echo json_encode(array('success' => FALSE, 'message' => "Please set coff based on input in timeoffice setting.."));
					exit(0);
		}
		$coff_check_qry = "";
		if($coff_based_on !== 'role' && $coff_based_on !== '0'){
			$emp_pick_arr   = $this->get_emp_data();
			$coff_check_val = $emp_pick_arr[$employee_code][$coff_based_on];
			if(!$coff_check_val){
				echo json_encode(array('success' => FALSE, 'message' => "Check input not exist for this Employee.."));
						exit(0);
			}
			$coff_check_qry = ' and FIND_IN_SET('.$coff_check_val.', cw_coff_settings.check_input)';
		}
		$check_inp_qry     = 'SELECT * from cw_coff_settings where FIND_IN_SET('.$category.', cw_coff_settings.category) '.$coff_check_qry;
		$check_inp_info    = $this->db->query("CALL sp_a_run ('SELECT','$check_inp_qry')");
		$check_inp_result  = $check_inp_info->result();
		$check_inp_info->next_result();	

		$coff_activated = $check_inp_result[0]->coff_activated;		
		$max_ot_hours   = $check_inp_result[0]->max_ot_hours;
		$halfday_min    = $check_inp_result[0]->halfday_min;
		$ot_activated   = $check_inp_result[0]->ot_activated;
		$halfday_hours  = $this->hours_mins_cal($halfday_min);
		$fullday_min    = $check_inp_result[0]->fullday_min;
		$max_ot_mins    = $this->hourstomins($max_ot_hours);
		//Get Active Salary Date that need to be process payroll
		$active_salary_date = $this->get_tos_active_salary_date();
		$salary_start_date = $active_salary_date[$category]['salary_start_date'];
		$salary_end_date   = $active_salary_date[$category]['salary_end_date'];
		if((int)$ot_type === 4){
			if((int)$coff_activated === 1){
				$excess_work_mins    = $this->hourstomins($approved_over_time);			
				//Check Hours reached Half Day
				if($excess_work_mins < $halfday_min){
					echo json_encode(array('success' => FALSE, 'message' => "Minimum $halfday_hours Hrs are mandatory for requesting C-Off"));
					exit(0);
				}
				//Get Shift Overtime record //approved_shift_ot+
				$shift_qry    = 'SELECT SUM(approved_ot_mins+approved_special_ot) as shiftot_mins from cw_time_entry where employee_code = "'.$employee_code.'" and att_date BETWEEN "'.$salary_start_date.'" and "'.$salary_end_date.'"';
				$shift_info   = $this->db->query("CALL sp_a_run ('SELECT','$shift_qry')");
				$shift_result = $shift_info->result();
				$shift_info->next_result();
				$final_ot_mins = (int)$shift_result[0]->shiftot_mins; 
				if($max_ot_mins > $final_ot_mins){
					echo json_encode(array('success' => FALSE, 'message' => "Total OT Hours in this month yet to reach your Max OT Hours($max_ot_hours)... Please Apply Overtime"));
					exit(0);
				}
			}else{
				echo json_encode(array('success' => FALSE, 'message' => "C-off Not Activated... Please Apply Overtime"));
				exit(0);
			}			
		}else{
			if((int)$ot_activated === 1){
				$ot_entry_qry    = 'SELECT SUM(CASE WHEN approval_status = 2 THEN TIME_TO_SEC(over_time)/60 END) AS approved_ot,SUM(CASE WHEN approval_status = 1 THEN TIME_TO_SEC(excess_work)/60 END) AS pending_ot from cw_overtime_entry where employee_code = "'.$employee_code.'" and entry_date BETWEEN "'.$salary_start_date.'" and "'.$salary_end_date.'"';
				$ot_entry_info   = $this->db->query("CALL sp_a_run ('SELECT','$ot_entry_qry')");
				$ot_entry_result = $ot_entry_info->result();
				$ot_entry_info->next_result();
				$approved_ot     = $ot_entry_result[0]->approved_ot;
				$pending_ot      = $ot_entry_result[0]->pending_ot;
				$ex_work_mins    = $this->hourstomins($approved_over_time);
				$total_ot_mins   = $approved_ot + $pending_ot + $ex_work_mins;
				if($max_ot_mins < $total_ot_mins){
					echo json_encode(array('success' => FALSE, 'message' => "Oops.. Already Reached Your Max OT Hours($max_ot_hours)..."));
					exit(0);
				}
			}else
			if((int)$ot_activated === 2){
				echo json_encode(array('success' => FALSE, 'message' => "Overtime Not Activated.."));
				exit(0);
			}
		}		
	}
	//prev view inputs
	public function get_previous_view($form_id){
		if($this->control_name === 'monthly_input' || $this->control_name === 'employee_self_portal'){
			$control_name = 'employees';
		}else{
			$control_name = $this->control_name;
		}
		$table_name   	  = "cw_".$control_name;
		$prime_table_id   = "prime_".$control_name."_id";
		$column_query = 'select 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;
	}

	public function gen_setting_comp_info(){
		$get_components = 'select prime_form_id,prime_module_id,label_name,view_name from `cw_form_setting` where prime_module_id = "employees" and field_type = 5 ORDER BY label_name';
		$get_components_info   = $this->db->query("CALL sp_a_run ('SELECT','$get_components')");
		$get_components_result = $get_components_info->result();
		$get_components_info->next_result();
		$components[""]        = "---- Select Component ----";
		foreach($get_components_result as $component){
			$prime_form_id     = $component->prime_form_id;
			$components_name   = $component->label_name;
			$components[$this->xss_clean($prime_form_id)] = $this->xss_clean($components_name);		
		}
		return $components;
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

						if($field_type === 5 || $field_type === 7){
							$pick_list_type      = (int)$pro_info['pick_list_type'];
							$imp_pick_list_val_1 = $pro_info['imp_pick_list_val_1'];
							$imp_pick_list_val_2 = $pro_info['imp_pick_list_val_2'];

							//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;
					}
				}
			}
		}
	}
	public function picklist_info(){
		if($this->control_name === "employee_log_report"){
			$this->control_name  = "employees";
		}		
		// UDY TEMP NNED TO REMOVE		
		$pro_qry   = [];
		$pro_qry[] = array("return"=>"form_info","qry"=>'select * from cw_form_setting where prime_module_id = "'.$this->control_name.'" and field_show = "1" and trans_status = "1" and FIND_IN_SET("'.$this->logged_user_role.'",user_right_for) and field_show = 1');
		if(count($pro_qry) > 0){
			$page_info_rslt         = $this->run_multi_qry($pro_qry);
			$pro_pick_list      = [];
			foreach($page_info_rslt->rslt->form_info as $key => $value){
				$field_type       = (int)$value->field_type;
				$table_show       = (int)$value->table_show;
				$search_show      = (int)$value->search_show;
				$input_view_type  = (int)$value->input_view_type;
				$field_show  	  = (int)$value->field_show;	

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

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

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

		$column_data_qry    = 'select email_table_email_column,cw_email_block.prime_email_block_id,email_block_for,email_block_type,email_block_table,email_block_column,email_name_table,email_table_column,email_table_email_column,email_table_list FROM cw_email_block INNER JOIN cw_email_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());

		// print_r($email_block_rsLt);die;

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

		//print_r($where_result);die;

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

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

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

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

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

		$attachment_qry  = 'SELECT prime_print_design_id,print_design FROM cw_print_design WHERE trans_status = 1';
		$attachment_info = $this->db->query("CALL sp_a_run ('SELECT','$attachment_qry')");
		$attachment_rlst = $attachment_info->result_array();
		$attachment_info->next_result();
		$attachment_rlst = array_reduce($attachment_rlst, function($result, $arr){			
			$result[$arr['prime_print_design_id']] = $arr;
			return $result;
		}, array());
		
		// echo "<pre>";
		// print_r($attachment_rlst);die;

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

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

				$where_trans      = "";
				$where_trans_info = explode(",",$email_block_table);
				foreach($where_trans_info as $trans_info){
					$where_trans .= "$trans_info.trans_status = 1 and ";
				}
				$where_trans      = rtrim($where_trans,'and ');
				$where_condition  = "";
				if($where_result){
					$where_condition    = str_replace('^','"',$where_result[$email_block_id]['where_condition']);
					$where_condition    = str_replace('@today_date@',date("Y-m-d"),$where_condition);
					$where_condition    = str_replace('@logged_id@',$this->logged_id,$where_condition);				
					$session_date_list  = array("logged_DMY"=>"d-m-Y","logged_YMD"=>"Y-m-d","logged_MY"=>"m-Y","logged_YM"=>"Y-m","logged_Y"=>"Y"); 
					foreach($session_result as $rslt){
						$session_value 	   = $rslt->session_value;
						if($session_value !== "access_data"){
							$exist_val = "@".$session_value."@";
							if($session_date_list[$session_value]){
								$date_formate      = $session_date_list[$session_value];
								$saved_session_val = date($date_formate);
							}else{
								$saved_session_val = $this->session->userdata($session_value);
							}
							$where_condition  = str_replace($exist_val,$saved_session_val,$where_condition);
						}
					}
				}
				
				$select_attach_column = rtrim($select_attach_column,' , ');
				$email_column = 'CONCAT_WS(",",'.$email_column.') as mail_column';
				//echo "email_column => $email_column , line_table_query => $line_table_query<br>";
				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,',');
				}	
				// echo "BSK $email_block_type :: $email_qry :: $get_to_mail :: $bcc_email :: $bcc_email_column <br/>";				
			}
		}
		// die;
		if($prime_result){
			$assign_date_formate_list  = array("DMY"=>"d-m-Y","YMD"=>"Y-m-d","DFY"=>"d F Y","MY"=>"F-Y","YM"=>"Y-F","D"=>"d","M"=>"M","Y"=>"Y");
			$data['email_sts'] = true;
			foreach($prime_result as $rslt){
				$count++;
				$map_column = explode(",",$prime_select_column);
				$td_line = "";
				foreach($map_column as $table_column){
					$map_column   = explode(".",$table_column);
					$column 	  = $map_column[1];
					$value        = $rslt->$column;
					$replace_val  = "@".$column."@";
					$email_design = str_replace($replace_val,$value,$email_design);
					$attachment   = str_replace($replace_val,$value,$attachment);
					foreach($assign_date_formate_list as $key=>$formate){
						$start         = "@".$key."_";
						$end           = "_".$key."@";
						$replace_val   = $start.$column.$end;
						$replace_val   = $start.$column.$end;
						$date_value    = date_create($value);
						$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);
					}
				}
			}
		}
		$get_attachment 	= '';
		if($attachment){
			$get_attachment 	= $this->get_email_attachment($attachment,$email_subject,$pdf_name);
		}
		if($get_to_mail){
			$mail_send_status = $this->send_mail_dynamic($mail_status_name,$get_to_mail,$config_result,$email_subject,$email_design,$bcc_mail,$get_attachment,$bcc_email_column);
		}else{
			$mail_send_status    = "";
		}
		return $mail_send_status;
	}
	public function get_autocomplete_data(){
		$search_term      = $this->input->post_get('term');		
		$search_qry       = 'select cw_custom_employees.prime_custom_employees_id value,CONCAT(cw_custom_employees.aadhar_card_no," - ",cw_custom_employees.emp_name) as label,cw_custom_employees.aadhar_card_no as display_name from cw_custom_employees where cw_custom_employees.trans_status = 1 and (cw_custom_employees.aadhar_card_no LIKE "%'.$search_term.'%") limit 0,50';
		$search_info      = $this->db->query("CALL sp_a_run ('SELECT','$search_qry')");
		$search_rslt      = $search_info->result_array();
		$search_info->next_result();
		if($search_rslt[0]){
			echo json_encode($search_rslt);
		}else{
			echo json_encode(array('success' => false, 'message' => "No Data Found..!"));
		}
	}
	
	//on change unique input validation
	public function input_uniq_validation(){
		$post_data           = $this->input->post('post_data');		
		$post_json_data      = json_encode($post_data);
		$valid_unique        = $this->db->query("CALL sp_validate_unique ('$post_json_data')");
		$valid_unique_rslt   = $valid_unique->result_array();
		$valid_unique->next_result();
		if($valid_unique_rslt[0]){
			echo json_encode(array('success' => FALSE, 'message' => "Unique Error..!Please View Unique Error Table?","table_info" => $valid_unique_rslt));
			exit(0);
		}else{
			echo json_encode(array('success' => TRUE, 'message' => "Proceed..!"));
		}
	}
	
	//function for validate a unique fields via procedure
	public function unique_procedure_valid($post_json_data){
		$validation_sts_arr  = array();
		//unique procedure call
		$valid_unique        = $this->db->query("CALL sp_validate_unique ('$post_json_data')");
		$valid_unique_rslt   = $valid_unique->result_array();
		$valid_unique->next_result();
		if($valid_unique_rslt[0]){
			$validation_sts_arr = $valid_unique_rslt;
			return $validation_sts_arr;
			// exit(0);
		}else{
			return $validation_sts_arr = array(1);
		}
	}

	//IFSC CODE BASED BANK DETAILS GET
	public function get_bank_details(){
		$ifsc_code		= $this->input->post("ifsc_code");
		$get_api_data	= $this->get_api_data($ifsc_code);
		$bank_name 		= $get_api_data->BANK;
		$bank_branch 	= $get_api_data->BRANCH;
		if($bank_name){
			echo json_encode(array('success'=>TRUE,'message'=>"",'bank_name' => $bank_name,"bank_branch"=>$bank_branch,'get_api_data'=>$get_api_data));
		}else{
			echo json_encode(array('success'=>false,'message'=>"IFSC code Wrong"));
		}
	}
	//API BASED ON IFSC CODE 
	public function get_api_data($ifsc_code) {
		$json = @file_get_contents("https://ifsc.razorpay.com/".$ifsc_code);
	    $arr = json_decode($json);
	    return $arr;
	}

	//TL AND PM FETCH BASED ON TEAM
	// public function tl_pm_fetch(){
	// 	$team           = $this->input->post("team");
	// 	//TEAM TABLE SELECT QUERY
	// 	$tl_pm_qry      = 'select cw_team.team,cw_team.tl_report,tl.emp_name tl_name,cw_team.manager_report,pm.emp_name pm_name from cw_team inner join cw_employees tl on cw_team.tl_report = tl.employee_code and tl.termination_status = 0 inner join cw_employees pm on cw_team.manager_report = pm.employee_code and pm.termination_status = 0 where cw_team.prime_team_id = "'.$team.'" and tl.trans_status = 1 and pm.trans_status = 1 and cw_team.trans_status = 1';
	// 	$tl_pm_info     = $this->db->query("CALL sp_a_run ('SELECT','$tl_pm_qry')");
	// 	$tl_pm_rslt     = $tl_pm_info->result_array();
	// 	$tl_pm_info->next_result();
	// 	echo json_encode(array('success' => true,'message' => 'Proceed.!','tl_pm_arr' => $tl_pm_rslt));
	// }
}
?>