MOON
Server: Apache
System: Linux nserver.cafsindia.com 4.18.0-553.104.1.lve.el8.x86_64 #1 SMP Tue Feb 10 20:07:30 UTC 2026 x86_64
User: cafsindia (1002)
PHP: 8.2.30
Disabled: NONE
Upload Files
File: /home/cafsindia/hrms_cafsinfotech_in/application_bk14FEB2026/controllers/Pdf_generation.php
<?php if ( ! defined('BASEPATH')) exit('No direct script is allowed');
require_once("Action_controller.php");
use DOMDocument;
class Pdf_generation  extends Action_controller{	
	private $emp_data_rslt;
	public function __construct(){
		parent::__construct('pdf_generation');
		if(!$this->Appconfig->isAppvalid()){
			redirect('config');
		}
	}
	// LOAD PAGE QUICK LINK,FILTERS AND TABLE HEADERS
	public function index(){
		//FILTER
		// $from_query    = 'select * from cw_form_setting where prime_module_id = "employees" and field_show = "1" 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();
		// $fliter_list   = $this->get_filter_data($form_result);
		// $data['fliter_list'] = $fliter_list;
		//DESIGN MODULES
		$remove_module = array("request","approval","direct_leave_entry","formm","offer_letter","custom_approval");
		$remove_module = implode('","', $remove_module ?? []);
		$print_module_qry 	 = 'SELECT print_info_module_id FROM `cw_print_info` where trans_status = 1 and print_info_module_id not in("'.$remove_module.'")';
		$print_module_info   = $this->db->query("CALL sp_a_run ('SELECT','$print_module_qry')");
		$print_module_result = $print_module_info->result();
		$print_module_info->next_result();
		$module_list[""]     = "---- Select Print From ----";
		foreach($print_module_result as $for){
			$module_id       = $for->print_info_module_id;
			$module_list[$module_id] = ucwords(str_replace("_", " ", $module_id));
		}
		$data['module_list'] = $module_list;
 		$payslip_based_on 	 = $this->company_info();
		$payslip_based_on	 = $payslip_based_on[0]->payslip_based_on;
		$data['payslip_based_on'] = ucwords(str_replace('_', '', $payslip_based_on));
		$data['key']         = $this->generateKey();
		$this->load->view("$this->control_name/manage",$data);
	}
	//RETREIVE TEMPLATE
	public function get_pdf_template(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$module_name   = $this->input->post("module_name");
		$template_qry  = 'SELECT prime_print_info_id,print_info_name FROM cw_print_design inner join cw_print_info on cw_print_info.prime_print_info_id = cw_print_design.print_design_for WHERE cw_print_info.print_info_module_id = "'.$module_name.'" and  cw_print_info.trans_status = 1 and cw_print_design.trans_status = 1';
		$template_info = $this->db->query("CALL sp_a_run ('SELECT','$template_qry')");
		$template_rslt = $template_info->result_array();
		$template_info->next_result();	
		echo json_encode(array('success' => true,'message' => '', 'template_rslt' => $template_rslt));
	}
	//DISABLE COMBINE PDF BASED ON TEMPLATE
	public function pdf_type_fetch(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$pdf_template  = $this->input->post("pdf_template");
		$pdf_type_qry  = 'SELECT cw_print_type.print_type as print_type FROM cw_print_info INNER JOIN cw_print_type ON cw_print_type.prime_print_type_id = cw_print_info.print_type WHERE cw_print_info.trans_status = 1 and prime_print_info_id = "'.$pdf_template.'" ';
		$pdf_type_info = $this->db->query("CALL sp_a_run ('SELECT','$pdf_type_qry')");
		$pdf_type_rslt = $pdf_type_info->result();
		$pdf_type_info->next_result();	
		$print_type    = $pdf_type_rslt[0]->print_type;
		echo $print_type;
	}
	//DYNAMIC COLUMN NAME RETREIVAL
	public function pdf_template_wise_data(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$pdf_template 	= $this->input->post("pdf_template");
		$column_qry  = 'SELECT concat(pdf_design_for) as pdf_design_for from cw_print_info where trans_status = 1 and prime_print_info_id = "'.$pdf_template.'"';
		$column_info = $this->db->query("CALL sp_a_run ('SELECT','$column_qry')");
		$column_rslt = $column_info->result_array();
		$column_info->next_result();
		$pdf_design_for	= $column_rslt[0]['pdf_design_for'];
		$pdf_design_for = rtrim($pdf_design_for,',');

		$payslip_based_on 	= $this->company_info();
		$payslip_based_on	= $payslip_based_on[0]->payslip_based_on;
		$form_setting_query= 'select label_name,view_name,pick_table,pick_list from cw_form_setting where prime_module_id = "employees" and label_name="'.$payslip_based_on.'" ORDER BY input_for,field_sort asc';
		$form_setting_info = $this->db->query("CALL sp_a_run ('SELECT','$form_setting_query')");
		$form_setting_rslt = $form_setting_info->result_array();
		$form_setting_info->next_result();

		$payslip_pick_table = $form_setting_rslt[0]['pick_table'];
		$payslip_pick_list 	= $form_setting_rslt[0]['pick_list'];
		$payslip_pick_arr 	= explode(',', $payslip_pick_list);
		$payslip_pick_list1 = $payslip_pick_arr[0];
		$payslip_pick_list2 = $payslip_pick_arr[1];
		$filter_qry = "";
		if($payslip_pick_table === "cw_category"){
			$filter_qry 	= " and prime_category_id != 1";
		}
		$column_qry	 = 'SELECT '.$payslip_pick_list.' from '.$payslip_pick_table.' where trans_status = 1 and '.$payslip_pick_list1.' in('.$pdf_design_for.') '.$filter_qry.'';
		$column_info = $this->db->query("CALL sp_a_run ('SELECT','$column_qry')");
		$column_rslt = $column_info->result();
		$column_info->next_result();
		$pick_key    = array_column($column_rslt ?? [], $payslip_pick_list1);
		$pick_val    = array_column($column_rslt ?? [], $payslip_pick_list2);
		$column_list = array_combine( $pick_key ?? [], $pick_val ?? []);
		$column_name = $form_setting_rslt[$payslip_based_on]['view_name'];
		$column_list = array("" => "---- $column_name ----") + $column_list;
		echo json_encode(array('success' => true,'message' => '', 'column_rslt' => $column_list));
	}
	//COMPANY INFORMATION
	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;
	}
	//GET EMPLOYEE CODE
	public function get_employees_list(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$column_name        = implode(',',array_filter($this->input->post('column_name') ?? []) ?? []);
		$process_month     	= $this->input->post('process_month');
		$module_name 	   	= $this->input->post('module_name');
		$pdf_template      	= $this->input->post('pdf_template');
		$where_column 	   	= $this->where_month_value($module_name,$pdf_template,$process_month);
		$where_column_arr 	= explode(',', $where_column ?? "");
		$where_column_count = count($where_column_arr ?? []);
		$where_month_col    = " $where_column";
		if((int)$where_column_count === 0){
			echo json_encode(array('success'=>FALSE,'message'=>"Please set Month Column for print setting"));
			exit(0);
		}
		$print_block_qry    = 'select print_block_table,prime_print_block_id from cw_print_info inner join cw_print_block on cw_print_block.print_block_for = cw_print_info.prime_print_info_id where cw_print_info.trans_status = 1 and cw_print_block.trans_status = 1 and prime_print_info_id = "'.$pdf_template.'"';
		$print_block_info   = $this->db->query("CALL sp_a_run ('SELECT','$print_block_qry')");
		$print_block_rslt   = $print_block_info->result_array();
		$print_block_info->next_result();
		$print_block_table  = explode(',', $print_block_rslt[0]['print_block_table']);
		$block_count	    = count($print_block_table ?? []);
		$block_id 		    = $print_block_rslt[0]['prime_print_block_id'];
		$where_qry          = 'select where_condition from cw_print_table_where where trans_status = 1 and cw_print_table_where.where_for_id = "'.$block_id.'"';
		$where_data         = $this->db->query("CALL sp_a_run ('SELECT','$where_qry')");
		$where_result       = $where_data->result_array();
		$where_data->next_result();
		$tbl_where_condition = $where_result[0]['where_condition'];
		$tbl_where_condition = str_replace('^','"',$tbl_where_condition);
		if((int)$block_count > 1){
			$print_table_qry   = 'select line_prime_table,line_prime_col,line_join_type,line_join_table,line_join_col,line_sort from cw_print_table where cw_print_table.trans_status = 1 and cw_print_table.print_table_for_id = "'.$block_id.'"';
			$print_table_info  = $this->db->query("CALL sp_a_run ('SELECT','$print_table_qry')");
			$print_table_rslt  = $print_table_info->result_array();
			$print_table_info->next_result();
			$print_table_count = count($print_table_rslt ?? []);
			$final_block_count = $block_count-1;
			if((int)$final_block_count !== (int)$print_table_count){
				echo json_encode(array('success'=>FALSE,'message'=>"Please Join Table!!!"));
				exit(0);
			}
			$cutome_table_check = array('transactions'=>'cw_transactions');
			$line_table_query   = "";
			foreach($print_table_rslt as $table_result){
				$line_prime_table = $table_result['line_prime_table'];
				$line_prime_col   = $table_result['line_prime_col'];
				$line_join_type   = $table_result['line_join_type'];
				$line_join_table  = $table_result['line_join_table'];
				$line_join_col    = $table_result['line_join_col'];
				$line_sort        = $table_result['line_sort'];
				$module_name      = str_replace("cw_","",$line_prime_table);
				$prime_id         = "prime_".$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 "; 
				}
			}
		}else{
			$line_table_query = $print_block_rslt[0]['print_block_table'];
		}
		$where_trans        = "";
		$where_trans_info   = explode(",",$print_block_rslt[0]['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 ');
		$payslip_based_on 	= $this->company_info();
		$payslip_based_on	= $payslip_based_on[0]->payslip_based_on;
		//stop_pay_status = 0 and 
		$final_qry 	  = 'select CONCAT("<option value =",cw_employees.employee_code," >",cw_employees.emp_name," - ",cw_employees.employee_code,"</option>") as result_data from '.$line_table_query.' where '.$where_trans.' and cw_employees.'.$payslip_based_on.' in('.$column_name.')'.$tbl_where_condition.' '.$where_month_col.' group by cw_employees.employee_code';
		$final_data   = $this->db->query("CALL sp_a_run ('SELECT','$final_qry')");
		$final_result = $final_data->result();
		$final_data->next_result();
		$result_data  = array_column($final_result ?? [],'result_data');
		$option       = "<option value=''>---- Select Employee ----</option>".implode('',$result_data ?? []);
		if(empty($final_result)){
			echo json_encode(array('success' => FALSE,'message' => "No Data Found for this Month"));
		}else{
			echo json_encode(array('success' => TRUE,'option' => $option));
		}	
	}
	//GENERATE PDF
	public function pdf_generation(){
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$suppressed_data     = $this->input->post('suppressed_data_val');
		$emp_codes           = implode(',',array_filter($this->input->post('pdf_block_employees') ?? []) ?? []);
		$emp_codes           = explode(",",$emp_codes ?? "");
		$emp_codes           = '"'.implode('","',$emp_codes ?? []).'"';
		$column_name         = implode(',',array_filter($this->input->post('column_name') ?? []) ?? []);
		$column_name         = explode(",",$column_name ?? "");
		$column_name         = '"'.implode('","',$column_name ?? []).'"';
		$payroll_process     = $this->input->post('pay_pro_type');	
		$pay_pro_type        = implode(',',array_filter($payroll_process ?? []) ?? []);
		$pay_pro_type        = explode(",",$pay_pro_type ?? "");
		$pay_pro_type        = '"'.implode('","',$pay_pro_type ?? []).'"';
		$process_month     	 = $this->input->post('process_month');
		$fliter_label        = $this->input->post('fliter_label');
		$fliter_type         = $this->input->post('fliter_type');
		$filter_cond         = $this->input->post('filter_cond');
		$fliter_val          = $this->input->post('fliter_val');
		$input_field_type    = $this->input->post('input_field_type');
		$process_by          = (int)$this->input->post('process_by');
		$pdf_type            = (int)$this->input->post('pdf_type');
		$process_mode  		 = (int)$this->input->post('process_mode');
		$pdf_template        = (int)$this->input->post('pdf_template');
		$filter_count        = count($fliter_label ?? []);
		$fliter_query        = "";
		$search_count        = 0;
		$module_name 	     = $this->input->post('module_name');
		$module_arr          = array('employees'=>'employees','increment'=>'employees','experience_letter'=>'employees'); 
		$company_information = $this->company_info();
		$encrypted_pdf       = $company_information[0]->encrypted_pdf;
		# COMPANY INFORM BASED PAYROLL SETTING
		$payroll_process_type= $company_information[0]->payroll_process_type;
		# FORM SETTING
		$form_set_qry        = 'SELECT transaction_type FROM cw_form_setting WHERE prime_module_id = "employees" AND label_name = "'.$payroll_process_type.'"';
		$form_set_info       = $this->db->query("CALL sp_a_run ('SELECT','$form_set_qry')");
		$form_set_rslt       = $form_set_info->result_array();
		$form_set_info->next_result();
		$trans_type          = (int)$form_set_rslt[0]['transaction_type'];
		
		if($trans_type === 4 || $module_name === 'increment'){
			$transaction_type= 'cw_employees';
		}else{
			$transaction_type= 'cw_transactions';
		}	
		$pay_process_type    = '';
		if($payroll_process){
			$pay_process_type= 'AND '.$transaction_type.''.'.'.$payroll_process_type.' IN ('.$pay_pro_type.')';
		}
		for($i = 0;$i <= (int)$filter_count;$i++){
			$db_name         = $fliter_label[$i];
			$table_name      = $fliter_type[$i];
			$db_cond         = $filter_cond[$i];
			$db_value        = $fliter_val[$i];
			$field_type      = $input_field_type[$i];
			if(($db_cond) && ($db_value)){
				$search_count++;
				if((int)$field_type === 4){
					$search_val = date("Y-m-d",strtotime($db_value));
				}else{
					$search_val = $db_value;
				}
				if($db_cond === "LIKE"){ $search_val = "$db_value%"; }
				if((int)$table_name === 1){ $fliter_query .= ' and cw_employees.'. $db_name ." ". $db_cond .' "'.$search_val.'"'; }
			}			
		}
		$payslip_based 	  = $this->company_info();
		$payslip_based_on = $payslip_based[0]->payslip_based_on;
		$block_qry        = 'SELECT prime_print_info_id,prime_print_block_id,print_block_name,print_block_type,print_block_table,print_block_column,folder_column,set_password,pdf_paper_size,pdf_sheet_type,password_column FROM cw_print_info INNER JOIN cw_print_block ON cw_print_block.print_block_for = cw_print_info.prime_print_info_id WHERE cw_print_info.trans_status = 1 AND cw_print_block.trans_status = 1 AND prime_print_info_id = "'.$pdf_template.'" AND print_info_module_id = "'.$module_name.'" and print_block_module_id = "'.$module_name.'"';
		$block_info  	  = $this->db->query("CALL sp_a_run ('SELECT','$block_qry')");
		$block_result     = $block_info->result_array();
		$block_info->next_result();
		$print_id   	  = $block_result[0]['prime_print_info_id'];
		$prime_print_block_id  = $block_result[0]['prime_print_block_id'];
		$pdf_set_password = $block_result[0]['set_password'];
		$pdf_paper_size   = $block_result[0]['pdf_paper_size'];
		$pdf_sheet_type   = $block_result[0]['pdf_sheet_type'];
		$design_name      = strtolower(str_replace(' ', '_', $block_result[0]['print_block_name']));
		$password_column  = $block_result[0]['password_column'];
		$design_qry       = 'SELECT print_design FROM cw_print_design WHERE print_design_for = "'.$print_id.'" AND 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_value = $design_result[0]->print_design;
		$print_design_value = str_replace('~','"',$print_design_value);
		$pwd_column 	  = "";
		if((int)$pdf_set_password === 1){
			$pwd_column   = ",$password_column";
		}
		
		if(!$pdf_set_password && !$pdf_paper_size && !$pdf_sheet_type){
			echo json_encode(array('success'=>FALSE,'message'=>"Pdf Settings Empty"));
			exit(0);
		}
	
		//GET TABLES JOIN(JOINT TABLE TAB)
		$table_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 and print_table_for_id = "'.$prime_print_block_id.'"';
		$table_data   = $this->db->query("CALL sp_a_run ('SELECT','$table_qry')");
		$table_result = $table_data->result_array();
		$table_data->next_result();
		foreach($table_result as $arr){
			$print_table_result[$arr['print_table_for_id']][] = $arr;
		}
		if($pdf_type === 1 && $process_by === 1){
			$emp_code_view  = "and cw_employees.employee_code in($emp_codes)";
		}else{
			$emp_code_view  = "and cw_employees.$payslip_based_on in($column_name)";      
		}
		$emp_qry 	  = 'SELECT prime_employees_id,emp_name,employee_code '.$pwd_column.' FROM `cw_employees` WHERE trans_status = 1 '.$emp_code_view.' '.$fliter_query.'';
		$emp_info     = $this->db->query("CALL sp_a_run ('SELECT','$emp_qry')");
		$emp_rslt 	  = $emp_info->result_array();
		$emp_info->next_result();
    
		$emp_rslt_arr =array();
		foreach ($emp_rslt as $key => $value) {
			$emp_rslt_arr[$value['employee_code']] = $value;
		}


		$emp_codes = array_values(array_column($emp_rslt_arr, 'employee_code'));
 		$db_name   = $this->config->item("db_name");
		if($db_name === "hare_hrms_db"){
			$tax_select_col    = 'SELECT emp_code,earning_total,otherin_1,taxsubsec_7,taxsubsec_3,taxsubsec_2,taxsubsec_5,taxsubsec_15,taxsubsec_12,taxsubsec_13,taxsubsec_16,taxsubsec_17,taxsubsec_20,taxsubsec_21,taxsubsec_22,tot_taxsec_1,tot_taxsec_2,tot_taxsec_3,taxsubsec_30,total_tax,edu_cess FROM cw_tax_calculation WHERE emp_code IN("'.$emp_code_arr.'") AND process_month ="'.$process_month.'"';
			$tax_select_data   = $this->db->query("CALL sp_a_run ('SELECT','$tax_select_col')");
			$tax_sel_col_rlst  = $tax_select_data->result_array();
			$tax_select_data->next_result();
			$tax_col_arr       = array();
			foreach($tax_sel_col_rlst as $key => $val){
				$tax_col_arr[$key][$val['emp_code']]= $val;   
			}
			$leave_bal_qry   = 'SELECT cw_employees.employee_code,cw_employees.emp_name,((cw_leave_opening.cl+cw_leave_opening.cl_credit)-(cw_leave_opening.cl_debit + cw_leave_opening.used_cl+ cw_leave_opening.pending_cl+ cw_leave_opening.encash_cl)) as balance_cl,((cw_leave_opening.el+cw_leave_opening.el_credit)-(cw_leave_opening.el_debit + cw_leave_opening.used_el+ cw_leave_opening.pending_el+ cw_leave_opening.encash_el)) as balance_el,((cw_leave_opening.compnl+cw_leave_opening.compnl_credit)-(cw_leave_opening.compnl_debit + cw_leave_opening.used_compnl+ cw_leave_opening.pending_compnl+ cw_leave_opening.encash_compnl)) as balance_compnl,((cw_leave_opening.echl+cw_leave_opening.echl_credit)-(cw_leave_opening.echl_debit + cw_leave_opening.used_echl+ cw_leave_opening.pending_echl+ cw_leave_opening.encash_echl)) as balance_echl,((cw_leave_opening.mal+cw_leave_opening.mal_credit)-(cw_leave_opening.mal_debit + cw_leave_opening.used_mal+ cw_leave_opening.pending_mal+ cw_leave_opening.encash_mal)) as balance_mal,((cw_leave_opening.pl+cw_leave_opening.pl_credit)-(cw_leave_opening.pl_debit + cw_leave_opening.used_pl+ cw_leave_opening.pending_pl+ cw_leave_opening.encash_pl)) as balance_pl,((cw_leave_opening.sl+cw_leave_opening.sl_credit)-(cw_leave_opening.sl_debit + cw_leave_opening.used_sl+ cw_leave_opening.pending_sl+ cw_leave_opening.encash_sl)) as balance_sl FROM `cw_employees` inner join cw_leave_opening on cw_leave_opening.employee_code = cw_employees.employee_code where cw_employees.trans_status = 1 and cw_employees.employee_code in ("'.$emp_code_arr.'")';
			$leave_bal_data  = $this->db->query("CALL sp_a_run ('SELECT','$leave_bal_qry')");
			$leave_bal_rslt  = $leave_bal_data->result_array();
			$leave_bal_data->next_result();
			$leave_bal_arr   = array();
			foreach($leave_bal_rslt as $key => $val){
				$leave_bal_arr[$key][$val['employee_code']]= $val;   
			}
		}
		$split_qry    = 'select split_info,split_colum from cw_print_split where trans_status = 1';
		$split_data   = $this->db->query("CALL sp_a_run ('SELECT','$split_qry')");
		$split_result_arr = $split_data->result_array();
		$split_data->next_result();
	
		foreach($split_result_arr as $arr){
			$split_result_arr[$arr['split_table_info']] = $arr;
		}

		$where_qry    = 'select where_condition,where_for_id from cw_print_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_arr = array();
		foreach($where_result as $arr){
			$where_result_arr[$arr['where_for_id']] = $arr;
		}		
		$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();

		$emp_codes_array  	= array_filter($emp_codes ?? []);
		$in_empcode 		= implode(',', $emp_codes_array ?? []);
		$in_empcode 		= str_replace(',', '","', $in_empcode);
		$folder_tbl_name 	= str_replace('cw_', '', $module_name);
		$folder_tbl_name   	= strtolower(str_replace(" ","_",$folder_tbl_name));
		$where_column 	    = $this->where_month_value($module_name,$pdf_template,$process_month);
		$where_column_arr 	= explode(',', $where_column ?? "");
		$where_column_count = count($where_column_arr ?? []);
		if($pdf_type === 1 && $process_by === 1){
			$emp_code_cond  = "and cw_employees.employee_code in(\"$in_empcode\")";
		}else{
			$emp_code_cond  = "and cw_employees.$payslip_based_on in($column_name)";      
		}
		$where_month_col    = "$where_column $emp_code_cond $pay_process_type";
		$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_arr 	= $form_data->result_array();
		$form_data->next_result();
		//while generating A Database Error Occurred -> added[13-03-2024]
		/*if($module_name === 'experience_letter'){
			$module_name = 'employees';
		}*/
		foreach($form_result_arr as $arr){
			$form_result_array[$arr['prime_module_id']][$arr['label_name']][] = $arr;
		}
		//For Increment Current and New Value Replace
		if($module_name === 'increment'){
			$inc_qry = 'SELECT cw_increment.apply_on , cw_increment.employee_code AS employee_code,cw_increment.effective_date , cw_increment.column_name , cw_increment.current_value , cw_increment.new_value from cw_increment WHERE cw_increment.trans_status = 1 AND cw_increment.apply_on ="'.$process_month.'"';
			$inc_data   = $this->db->query("CALL sp_a_run ('SELECT','$inc_qry')");
			$inc_rslt   = $inc_data->result_array();
			$inc_data->next_result();
			$inc_arr    = array();
			foreach($inc_rslt as $arr){
				$inc_arr[$arr['employee_code']][$arr['column_name']] = $arr;
			}
		} 
		//Get Payslip based on column name - START
		$module_name        = $module_arr[$module_name];
		$payslip_column_arr = $form_result_array[$module_name][$payslip_based_on][0];
		$pick_table         = $payslip_column_arr['pick_table'];
		$pick_list          = $payslip_column_arr['pick_list'];
		$name_qry           = 'select '.$pick_list.' from '.$pick_table.' where trans_status = 1';
		$name_data          = $this->db->query("CALL sp_a_run ('SELECT','$name_qry')");
		$name_result        = $name_data->result_array();
		$name_data->next_result();
		$pick_list_arr      = explode(",",$pick_list);
		$pick_id            = $pick_list_arr[0];
		$pick_name          = $pick_list_arr[1];
		$payslip_arr        = array();
		foreach ($name_result as $key => $value) {
			$payslip_arr[$value[$pick_id]] = $value[$pick_name];
		}
		$form_setting_qry   = 'select label_name,view_name,transaction_type from cw_form_setting where prime_module_id="employees" and transaction_type in("2","3") and trans_status =1';
		$form_setting_data  = $this->db->query("CALL sp_a_run ('SELECT','$form_setting_qry')");
		$form_col_rslt      = $form_setting_data->result_array();
		$form_setting_data->next_result();
		$label_name         = implode(",",array_column($form_col_rslt ?? [],'label_name') ?? []);
		foreach($form_col_rslt as $key => $val){
			if((int)$val['transaction_type'] === 2){
				$form_rslt['earnings'][$val['label_name']] = $val['view_name'];
				// $form_rslt['earnings']   = [$val['label_name']];
			}else
			if((int)$val['transaction_type'] === 3){
				// $form_rslt['deductions'] = [$val['label_name']];
				$form_rslt['deductions'][$val['label_name']] = $val['view_name'];
			}
		}
		$resigned_emp_qry ='SELECT min(resignation_date)as min_resignation_date,max(last_working_date) as max_last_working_date  FROM cw_employees WHERE termination_status = 1 and DATE_FORMAT(last_working_date, "%m-%Y") = "'.$process_month.'"';
		$res_emp_data   = $this->db->query("CALL sp_a_run ('SELECT','$resigned_emp_qry')");
		$res_emp_rslt   = $res_emp_data->result_array();
		$res_emp_data->next_result();
		$min_res_date   = $res_emp_rslt[0]['min_resignation_date'];
		if($process_mode === 1){ //GENERATE
			$final_qry_array	= $this->load_all_data($block_result,$print_table_result,$form_result_array,$where_result_arr,$split_result_arr,$where_month_col,$process_month,$in_empcode,$payslip_based_on);
			$final_qry 			= $final_qry_array['final_qry'];
			$split_array 		= $final_qry_array['split_array'];
			$map_column 		= $final_qry_array['map_column'];
			$block_result 		= $final_qry_array['block_result'];
			$assign_date_formate_list  = $final_qry_array['assign_date_formate_list'];
			$final_qry_data     = $this->db->query("CALL sp_a_run ('SELECT','$final_qry')");
			$final_qry_result   = $final_qry_data->result();
			$final_qry_data->next_result();
			if(!$final_qry_result){
				echo json_encode(array('success'=>FALSE,'message'=>"NO Data Available...",'table_data'=>""));
				exit(0);
			}
			$print_block_columns = $block_result[0]['print_block_column'];			
			
			$print_type_query = 'select print_type from cw_print_info where prime_print_info_id="'.$pdf_template.'" and trans_status =1'; 
			$print_type_data  = $this->db->query("CALL sp_a_run ('SELECT','$print_type_query')");
			$print_type_rslt  = $print_type_data->result_array();
			$print_type_data->next_result(); 
			$print_type_id    = $print_type_rslt[0]['print_type'];

			if($print_type_id === 56){ //Only for FandF Template HOLD
				$fandf_trans_qry   = 'select '.$print_block_columns.' from cw_transactions inner join cw_employees on cw_employees.employee_code = cw_transactions.employee_code where cw_transactions.trans_status=1 and cw_transactions.stop_pay_status =1 and cw_transactions.transactions_month between DATE_FORMAT("'.$min_res_date.'", "%m-%Y") AND "'.$process_month.'"';
				$fandf_trans_data   = $this->db->query("CALL sp_a_run ('SELECT','$fandf_trans_qry')");
				$fandf_trans_rslt   = $fandf_trans_data->result_array();
				$fandf_trans_data->next_result();
				$fandf_emp_result = array();
				foreach ($fandf_trans_rslt as $row){
					$employee_code = $row['employee_code'];
					foreach($row as $key => $value){
						if($key !== 'employee_code' && $key !== 'transactions_month'){
							$label_name = $key;
							$process_month = $row['transactions_month'];
							if(!isset($fandf_emp_result[$employee_code])){
								$fandf_emp_result[$employee_code] = array();
							}
							if(!isset($fandf_emp_result[$employee_code][$label_name])){
								$fandf_emp_result[$employee_code][$label_name] = array();
							}
							$fandf_emp_result[$employee_code][$label_name][$process_month] = $value;
						}
					}
				}
			}

			$tble_line    = "";
			$print_design = "";
			foreach($block_result as $block){
				$print_block_type      = (int)$block['print_block_type'];
				$print_block_column    = $block['print_block_column'].',folder_column.folder_column_name';
				$pdf_paper_size        = $block['pdf_paper_size'];
				$pdf_sheet_type        = $block['pdf_sheet_type'];
				$set_password          = (int)$block['set_password'];
				if($final_qry_result){
					$data['print_sts'] = true;
					$emp_detail_arr    = array();
					$emp_data_arr 	   = array();
					$final_data_rslt   = array();
					foreach($final_qry_result as $rslt){
						$employee_code = $rslt->employee_code;
						$count++;
						$map_column    = explode(",",$print_block_column);
						$td_line       = "";
						$print_design  = $print_design_value;
						if($employee_code && (int)$print_type_id === 56 && $db_name !== 'rebar_hrms_db'){
							$print_design = $this->fandf_hold_payslip($print_design,$employee_code,$process_month,$form_rslt,$fandf_emp_result);
						}
						if($employee_code){
							$inc_data      = $inc_arr[$employee_code]; 
							$print_design = $this->increment_replace($print_design,$inc_data);
						}
						foreach($map_column as $table_column){
							$map_column   = explode(".",$table_column);
							$column 	  = $map_column[1];
							$value        = $rslt->$column;
							$replace_val  = "@".$column."@";
							if($column === 'employee_code'){
								$emp_code = $value;
							}else
							if($column === 'folder_column_name'){
								//$payslip_based_id = $value;
								$payslip_based_id   = strtolower(str_replace(" ", "_", $value));
								$payslip_based_desc = strtolower(str_replace(" ", "_", $payslip_arr[$value]));
							}
							if($column == 'net_pay'){
								$value         = $rslt->$column;
								//$value         = $value.".00";
								$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);
							}
							$today_date        = date('d-m-Y');
							$print_design      = str_replace("@today_date@",$today_date,$print_design);
							if($split_array[$replace_val]){
								//Process split informtion 
								$process_function = $split_array[$replace_val];	
								if((int)$process_function === 1){
									$transactions_month = $final_qry_result[0]->transactions_month;
									$employee_code      = $final_qry_result[0]->employee_code;
									$loan_info = $this->get_loan_value($transactions_month,$employee_code);
									$print_design = str_replace($replace_val,$loan_info,$print_design);	
								}
							}else{
								if($print_block_type === 1){
									$print_design = str_replace($replace_val,$value,$print_design);
									foreach($assign_date_formate_list as $key=>$formate){
										if($column == 'transactions_month'){//transactions month static updated
											$start         = "@".$key."_";
											$end           = "_".$key."@";
											$replace_val   = $start.$column.$end;
											$value         = date('Y-m-d',strtotime("01-".$rslt->$column));
											$date_value    = date_create($value);
											$replace_value = strtoupper(date_format($date_value,$formate));
											$print_design  = str_replace($replace_val,$replace_value,$print_design);
										}else{//not static month updated
											$start         = "@".$key."_";
											$end           = "_".$key."@";
											$replace_val   = $start.$column.$end;
											$replace_val   = $start.$column.$end;
											$date_value    = date_create($value);
											if($date_value){
												$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));
									if(($value === "") || ($value === "0.00") || ($value === "0") || (!$value)){
										$th_line = "";
									}else{
										$th_line .= "<th style='text-align:center;'>$head_name</th>";
									}
								}
							}
						}
						if($print_block_type === 2){
							if($count === 1){
								if(($value === "") || ($value === "0.00") || ($value === "0") || (!$value)){
									$th_line = "";
								}else{
									$th_line  = "$th_line";
									$tr_line .= "<tr>$td_line</tr>";
								}
							}
						}
						// Commented for tamil pdf issue. don't remove
						if((int)$suppressed_data === 1){
							$print_design = str_replace("<br>","",$print_design);
						}
						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);
						}
						$emp_data_arr[$payslip_based_id][$emp_code]['emp_code'] 		  = $emp_code;
						$emp_data_arr[$payslip_based_id][$emp_code]['payslip_based_id']   = $payslip_based_id;
						$emp_data_arr[$payslip_based_id][$emp_code]['payslip_based_desc'] = $payslip_based_desc;
						$emp_data_arr[$payslip_based_id][$emp_code]['print_design'] 	  = $print_design;
						if((int)$set_password === 1){
							$password_column = explode(',', $block_result[0]['password_column']);
							$password_col = "";
							foreach ($password_column as $pwd_key => $pwd_value) {
								$pwd_field_type = $form_result_array['employees'][$pwd_value][0]['field_type'];
								if((int)$pwd_field_type === 4){
									$password_col 	.= date('d-m-Y',strtotime($emp_rslt_arr[$emp_code][$pwd_value]));
								}else{
									$password_col 	.= $emp_rslt_arr[$emp_code][$pwd_value];
								}
							}
						}
						$emp_data_arr[$payslip_based_id][$emp_code]['pwd_column']		= $password_col;
						$emp_data_arr[$payslip_based_id][$emp_code]['set_password']	= $set_password;
						$emp_data_arr[$payslip_based_id][$emp_code]['pdf_sheet_type']	= $pdf_sheet_type;
						$emp_data_arr[$payslip_based_id][$emp_code]['pdf_paper_size']	= $pdf_paper_size;
						$emp_data_arr[$payslip_based_id][$emp_code]['process_month']	= $process_month;
					}
				}
			}
			if($pdf_type === 1){
				$folder_arr = $this->single_pdf($emp_data_arr,$design_name,$payslip_based_on,$folder_tbl_name,$process_month,$suppressed_data,$encrypted_pdf,$tax_col_arr,$fin_result,$leave_bal_arr);
			}else
			if($pdf_type === 2){ // && $pdf_template === 1
				$folder_arr = $this->combine_pdf($emp_data_arr,$design_name,$payslip_based_on,$folder_tbl_name,$process_month,$suppressed_data,$encrypted_pdf,$tax_col_arr,$fin_result,$leave_bal_arr);
			}	
		}else
		if($process_mode === 2){ //VIEW
			$payslip_based_on 	= $this->company_info();
			$payslip_based_on	= $payslip_based_on[0]->payslip_based_on;
			$form_setting_qry   = 'select label_name,view_name,pick_table,pick_list from cw_form_setting where prime_module_id = "employees" and trans_status = 1 and label_name = "'.$payslip_based_on.'"';
			$form_setting_info  = $this->db->query("CALL sp_a_run ('SELECT','$form_setting_qry')");
			$form_setting_rslt  = $form_setting_info->result();
			$form_setting_info->next_result();
			$payslip_pick_table = $form_setting_rslt[0]->pick_table;
			$payslip_pick_list 	= $form_setting_rslt[0]->pick_list;
			$payslip_pick_arr 	= explode(',', $payslip_pick_list);
			$payslip_pick_list1 = $payslip_pick_arr[0];
			$payslip_pick_list2 = $payslip_pick_arr[1];
			$emp_code_qry       = '';
			if($pdf_type === 1){
				$emp_code_qry   = 'and employee_code in("'.$in_empcode.'")';
			}else{
				$emp_code_qry   = 'and '.$payslip_pick_table.'.'.$payslip_pick_list1.' IN ('.$column_name.') GROUP BY payslip_based_desc';
			}
			$emp_query = 'select '.$payslip_pick_table.'.'.$payslip_pick_list1.' as '.$payslip_based_on.','.$payslip_pick_table.'.'.$payslip_pick_list2.'  as payslip_based_desc,employee_code,emp_name from cw_employees inner join '.$payslip_pick_table.' on '.$payslip_pick_table.'.'.$payslip_pick_list1.' = cw_employees.'.$payslip_based_on.' where cw_employees.trans_status = 1 '.$emp_code_qry.'';	
			$emp_info  = $this->db->query("CALL sp_a_run ('SELECT','$emp_query')");
			$emp_rslt  = $emp_info->result_array();
			$emp_info->next_result();
			if($pdf_type === 1){ //SINGLE
				foreach($emp_rslt as $arr){
					$folder_arr[$arr['employee_code']] = $arr;
				}
			}else{ //COMBINED
				foreach($emp_rslt as $arr){
					$folder_arr[$arr['payslip_based_desc']] = $arr;
				}
			}
		}
		$dw_all    	= $folder_tbl_name."/".$design_name."/".$process_month;
		$table_data = $this->view_emp_details($emp_codes_array,$process_by,$process_mode,$folder_arr,$column_name,$emp_rslt,$dw_all,$tbl_name,$folder_tbl_name,$design_name,$process_month,$encrypted_pdf,$pdf_type);
		echo json_encode(array('success' => true,'message' => '', 'table_data' => $table_data));
	}

	//SINGLE PDF GENERATION
	public function single_pdf($emp_data_arr,$design_name,$payslip_based_on,$folder_tbl_name,$process_month,$suppressed_data,$encrypted_pdf,$tax_col_arr,$fin_result,$leave_bal_arr){
		$get_pdf_design = "";
		$form_head_flag = '0';
		$count          = 0;
		foreach($emp_data_arr as $based_on => $emp_data){
			$overall_count          = count($emp_data ?? []);
			$sum_arr = array();
			foreach($emp_data as $i => $emp_detail){
				$count              = $count+1;
				$db_name            = $this->config->item("db_name");
				$emp_code 		    = $emp_detail['emp_code'];
				$process_month      = $emp_detail['process_month'];
				if((int)$encrypted_pdf === 1){
					$file_name      = $db_name."_".$emp_code."_".$process_month; 
					$enc_file       = $this->encryptFilename($file_name,$db_name);	
					$enc_file_name  =  $enc_file."_".$emp_code;	
				}else{
					$enc_file_name  = $emp_code;
				}
				$cate_name   	    = str_replace('/', '_',strtolower(str_replace(' ', '_', $emp_detail['payslip_based_desc'])));
				$print_design 	    = $emp_detail['print_design'];
				$print_design       = str_replace('~','"', $print_design);
				//only for HARE db
				if($db_name === 'hare_hrms_db'){
					$print_design   = $this->tax_with_payslip($print_design,$emp_code,$tax_col_arr,$process_month,$fin_result,$leave_bal_arr);
				}
				if($design_name === "form_wr"){//[MS-10-07-2024] WAGE REGISTER
					$wrdom        = new \DOMDocument();
					$wrdom->loadHTML($print_design);
					$xpath      = new \DOMXPath($wrdom);
					$table_data = $xpath->query("//table[@id='form_wr_table']/tbody/tr/td");
					$trow 	   .= '<tr><td style="text-align:center">'.$count.'</td>';			
					$final_row  = '<tr><td style="text-align:center;font-weight: bold;">Grand Total</td>';		
					$z       = 0;
					for($x = 1 ; $x < $table_data->length; $x++ ){
						$final_tfoot = '';
						$sum_arr[$x + 1] += (int)trim($table_data->item($x)->nodeValue);
						$trow  .= '<td style="text-align:center;">'.$table_data->item($x)->nodeValue.'</td>';
						if($sum_arr[$x +1] === 0){
							$final_tfoot .= '<td style="text-align:center;font-weight: bold;"></td>';
						}else{
							$final_tfoot .= '<td style="text-align:center;font-weight: bold;">'.$sum_arr[$x +1].'</td>';
						}
						if($count === $overall_count){
							$final_row .= $final_tfoot;
						}				
					}
					$final_row .= '</tr>';
					$trow      .= '</tr>';
					if($count === $overall_count){
						$print_design = $this->get_table($print_design,$trow,$final_row);
					}
					$count            = $count +1;	
				}
				// if($emp_code && (int)$pdf_template === 45){
				// 	$print_design = $this->fandf_hold_payslip($print_design,$emp_code,$process_month,$form_rslt,$fandf_emp_result);
				// }
				$set_password 	    = $emp_detail['set_password'];
				$pdf_sheet_type     = $emp_detail['pdf_sheet_type'];
				$pdf_paper_size     = $emp_detail['pdf_paper_size'];
				$pwd_column 	    = $emp_detail['pwd_column'];
				$pwd_column 	    = preg_replace('/[^a-zA-Z0-9]/s','',$pwd_column);

				$fontPath = FCPATH . 'fonts/BalooThambi2-Regular.ttf'; // Front controller path (public folder)
				$fontPath = str_replace('\\', '/', realpath($fontPath));

				// Debugging (remove in production)
				//table tr { line-height: 20px !important; } deleted for Pothys gayathri mam asked on
				//06apr2024
				if($design_name !== 'form_wr'){
					$lineh = "";
					if($this->config->item("db_name") !== 'pothys_hrms_db'){
						$lineh      = 'table tr { line-height: 20px !important; }';
					}
					$print_design   = "<!DOCTYPE html><head><style>	@font-face{ font-family: 'Baloo Thambi 2';src: url('$fontPath') format('truetype');}table td.fr-highlighted,.fr-view table th.fr-highlighted{border:1px solid black !important;vertical-align: text-top;}$lineh table {border-collapse: collapse !important;page-break-inside: avoid !important;}table td{vertical-align: text-top !important;}#earnings td{height : 16px;font-size:12px;}#earnings th{border-bottom:1px solid black;font-size:12px;}#earnings first-th{width:45%;}#deductions td{height : 16px;font-size:12px;}#net_pay td{height : 16px;}</style></head><body>".$print_design."</body></html>";

					//echo "GS: GET PDF CALLED".$enc_file_name;
					$fetchURL = $this->get_pdf($design_name,$pdf_paper_size,$pdf_sheet_type,$pdf_set_password,$pdf_sheet_per_page,$print_id,$print_design,$column_name,$payslip_month,$enc_file_name,$process_by,$folder_tbl_name,$cate_name,$process_month,$suppressed_data,$payslip_based_on,$pwd_column);
					$folder_arr[$emp_code] = 'pdf_generation/'.$folder_tbl_name."/".$design_name."/".$process_month."/".$payslip_based_on."_".$cate_name;
				}
			}
			//ONLY FOR WAGE REGISTER [MS 08-07-2024]
			if($design_name === 'form_wr'){
				$lineh = "";
				$print_design   = "<!DOCTYPE html><head><style>table td.fr-highlighted,.fr-view table th.fr-highlighted{border:1px solid black !important;vertical-align: text-top;}$lineh table {border-collapse: collapse !important;page-break-inside: avoid !important;}table td{vertical-align: text-top !important;}#earnings td{height : 16px;font-size:12px;}#earnings th{border-bottom:1px solid black;font-size:12px;}#earnings first-th{width:45%;}#deductions td{height : 16px;font-size:12px;}#net_pay td{height : 16px;}</style></head><body>".$print_design."</body></html>";
				
				$fetchURL = $this->get_pdf($design_name,$pdf_paper_size,$pdf_sheet_type,$pdf_set_password,$pdf_sheet_per_page,$print_id,$print_design,$column_name,$payslip_month,$enc_file_name,$process_by,$folder_tbl_name,$cate_name,$process_month,$suppressed_data,$payslip_based_on,$pwd_column);
				$folder_arr[$emp_code] = 'pdf_generation/'.$folder_tbl_name."/".$design_name."/".$process_month."/".$payslip_based_on."_".$cate_name;
			}
		}
		return $folder_arr;
	}
	//COMBINE PDF GENERATION
	public function combine_pdf($combine_data_arr,$design_name,$payslip_based_on,$folder_tbl_name,$process_month,$suppressed_data,$encrypted_pdf,$tax_col_arr,$fin_result,$leave_bal_arr){	
		foreach($combine_data_arr as $based_on => $emp_data_arr){	
			$get_pdf_design   = "";	
			foreach($emp_data_arr as $i => $emp_detail){
				$db_name           = $this->config->item("db_name");
				$emp_code 		   = $emp_detail['emp_code'];
				$process_month     = $emp_detail['process_month'];
				$cate_id 		   = str_replace('/', '_',strtolower(str_replace(' ', '_', $emp_detail['payslip_based_id'])));
				$cate_name   	   = str_replace('/', '_',strtolower(str_replace(' ', '_', $emp_detail['payslip_based_desc'])));
				$print_design 	   = $emp_detail['print_design'];
				$print_design      = str_replace('~','"', $print_design);
				if((int)$encrypted_pdf === 1){
					$file_name     = $db_name."_".$cate_id."_".$process_month; 
					$enc_file      = $this->encryptFilename($file_name,$db_name);	
					$enc_file_name =  $enc_file."_".$cate_name;	
				}else{
					$enc_file_name = $cate_name;
				}
				//only for HARE db
				if($db_name === 'hare_hrms_db'){
					$print_design   = $this->tax_with_payslip($print_design,$emp_code,$tax_col_arr,$process_month,$fin_result,$leave_bal_arr);
				}
				$lineh     = "";
				if($db_name !== 'pothys_hrms_db'){
					$lineh = 'table tr { line-height: 20px !important; }';
				}
				$get_pdf_design   .= "<div style='page-break-inside: avoid;' class='pager'>$print_design</div>";			
				$final_rslt 	   = "<!DOCTYPE html><head><style>table td.fr-highlighted,.fr-view table th.fr-highlighted{border:1px solid black !important;vertical-align: text-top;}$lineh table{border-collapse: collapse !important;}table td{vertical-align: text-top !important;}#earnings td{height : 16px;font-size:12px;}#earnings th{border-bottom:1px solid black;font-size:12px;}#earnings first-th{width:45%;}#deductions td{height : 16px;font-size:12px;}#net_pay td{height : 16px;}</style></head><body>".$get_pdf_design."</body></html>";
			}
			//SUPPRESS DATA
			if((int)$suppressed_data === 1){
				$dom     = new \DOMDocument();
				$dom->loadHTML($final_rslt);
				$xpath   = new \DOMXPath($dom);
				
				
				$pagers  = $xpath->query("//div[contains(@class, 'pager')]");
				foreach($pagers as $pager){
					# EARNINGS	
					$earn_ct = 0;
					$trs     = $xpath->query(".//table[@id='earnings']/tbody/tr", $pager);
					foreach($trs as $row){
						$tds       = $row->getElementsByTagName('td');				
						$lastIndex = $tds->length - 1; // Index of the last column		
						if($tds->item($lastIndex)->nodeValue !== '0.00' && $tds->item($lastIndex)->nodeValue !== ''){
							$earn_ct++;
						}				
						for($i = 0; $i <= $tds->length; $i++){
							if($tds->item($i)->nodeValue === '0.00' ){
								if($row->parentNode){
									$row->parentNode->removeChild($row);
									break;
								}					
							}
						}
						$allEmpty = true;
						for($i = 0; $i < $tds->length; $i++){
							if($tds->item($i)->nodeValue !== ''){
								$allEmpty = false;
								break;
							}
						}
						if($allEmpty && $row->parentNode){
							// If all values are empty, remove the parent node
							$row->parentNode->removeChild($row);
						}
					}
					# DEDUCTIONS
					$ded_ct  = 0;
					$trs_ded =  $xpath->query(".//table[@id='deductions']/tbody/tr", $pager);
					foreach($trs_ded as $row_ded){
						$tds_ded   = $row_ded->getElementsByTagName('td');
						$lastIndex = $tds_ded->length - 1; // Index of the last column
						if($tds_ded->item($lastIndex)->nodeValue !== '0.00' && $tds_ded->item($lastIndex)->nodeValue !== ''){
							$ded_ct++;
						}
						for($i = 0; $i <= $tds_ded->length; $i++){
							if($tds_ded->item($i)->nodeValue === '0.00' ){
								if($row_ded->parentNode){ 
									$row_ded->parentNode->removeChild($row_ded);
									break;
								}						
							}
						}
						$Empty = true;
						for($i = 0; $i < $tds_ded->length; $i++){
							if($tds_ded->item($i)->nodeValue !== ''){
								$Empty = false;
								break;
							}
						}
						if($Empty && $row_ded->parentNode){
							// If all values are empty, remove the parent node
							$row_ded->parentNode->removeChild($row_ded);
						}	   
					}
					# ADD COLUMNS TO BALANCE STYLE PURPOSE
					if($earn_ct > $ded_ct){	
						$trs_ded_app	= $xpath->query(".//table[@id='deductions']/tbody/tr", $pager);
						$difference     = abs($ded_ct - $earn_ct);
						$last_row_index = $trs_ded_app->length - 1;
						$last_row       = $trs_ded_app->item($last_row_index);
						for($i = 0; $i < $difference; $i++){ #CREATE NEW ROW
							$z = 0;
							$new_row    = $dom->createElement('tr');
							if($last_row){
								$cols       = $last_row->getElementsByTagName('td'); 
								foreach($cols as $col){
									$empty_cell = $dom->createElement('td');
									$style      = $last_row->childNodes->item($z)->getAttribute('style');
									$empty_cell->setAttribute('style', $style);
									$new_row->appendChild($empty_cell);
									$z++;
								}
								$last_row_parent = $last_row->parentNode;
								$last_row_parent->appendChild($new_row);
							}							
						}
					}else
					if($ded_ct > $earn_ct){
						$trs_ear_app    = $xpath->query(".//table[@id='earnings']/tbody/tr", $pager);
						$difference     = abs($ded_ct - $earn_ct);
						$last_row_index = $trs_ear_app->length - 1;
						$last_row       = $trs_ear_app->item($last_row_index);
						for($i = 0; $i < $difference; $i++){ #CREATE NEW ROW
							$j = 0;
							$new_row    = $dom->createElement('tr');
							if($last_row){
								$cols       = $last_row->getElementsByTagName('td');
								foreach($cols as $col){
									$empty_cell = $dom->createElement('td');
									$style      = $last_row->childNodes->item($j)->getAttribute('style');
									$empty_cell->setAttribute('style', $style);
									$new_row->appendChild($empty_cell);
									$j++;
								}
								$last_row_parent = $last_row->parentNode;
								$last_row_parent->appendChild($new_row);	
							}								
						}	
					}
				}
				//For FandF Design 
				$xpath = new \DOMXPath($dom);
				foreach($xpath->query('//tr') as $tr){
					$tds = $tr->getElementsByTagName('td');
					for($i = 0; $i <= count($tr ?? []); $i++){
						// get table cell value.
						$table_cell_value = $tds->item($i)->nodeValue;
						if($table_cell_value === '0.00'){
							$tr->parentNode->removeChild($tr);
							break; 
						}
					}
				}
				// get the result
				$saved_html = preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $dom->saveHTML());
			}else{
				$saved_html    = $final_rslt;
			}
			$design_name 	 = str_replace(' ', '_', $design_name);
			$cate_name 		 = str_replace(' ', '_', $cate_name);
			$folder_tbl_name = str_replace(' ', '_', $folder_tbl_name);
			$folder 	     = 'pdf_generation/'.$folder_tbl_name."/$design_name/$process_month/".$payslip_based_on."_".$cate_name;
			$file_type 	     = ".pdf";
			$folder          = strtolower($folder);
			//PATH CREATION TO STORE THE FILES 
			$oldmask         = umask(0);
			if(!file_exists($folder)){
				mkdir($folder, 0777, true); # IF NOT CREATE
			}
			//FILE WRITE AS HTML
			file_put_contents($folder."/".$enc_file_name.".html" , $saved_html);
			chmod($folder."/".$enc_file_name.".html", 0777);
			umask($oldmask);
			$dw_all      	= $folder_tbl_name."/".$design_name."/".$process_month;
			$directory      = str_replace('application/controllers', '', __DIR__);
			$html_file_name = $directory.$folder."/".$enc_file_name.".html";	
			$pdf_file_name  = $directory.$folder."/".$enc_file_name.".pdf";	
			if(file_exists($html_file_name)){
				//CONVERT HTML FILE TO PDF 
				$command    = "xvfb-run  wkhtmltopdf --orientation portrait $html_file_name $pdf_file_name";
				$output     = shell_exec($command);
				$folder_arr[$cate_name] = array('folder' => $folder,'file_name' => $enc_file_name,'cate_id' => $cate_id,'cate_name' => $cate_name);
				unlink($html_file_name);
			}
		}
		return $folder_arr;
	}
	//               WAGE REGISTER PROCESS START  [MS-10-07-2024]
	public function get_table($print_design,$get_row,$final_tot_row){
		$dom             = new \DOMDocument();
		$dom->loadHTML($print_design);
		$xpath           = new \DOMXPath($dom);
		$trs     		 = $xpath->query("//table[@id='form_wr_table']/tbody/tr");
		foreach($trs as $row){
			$row->parentNode->removeChild($row);
		}
		$new_row         = $dom->createDocumentFragment();
		$new_row->appendXML($get_row); 
		$table_body      = $dom->getElementById("table_body");
		$table_body->appendChild($new_row);
		//For Total Row Purpose
		$tfrow            = $dom->createDocumentFragment();
		$tfrow->appendXML($final_tot_row); 
		$tfoot           = $dom->getElementById("table_body");
		$tfoot->appendChild($tfrow);
		$saved_html      = $dom->saveHTML();
		return $saved_html;
	}
	//               WAGE REGISTER PROCESS END    [MS-10-07-2024]
	public function tax_with_payslip($print_design,$emp_code,$tax_col_arr,$process_month,$fin_result,$leave_bal_arr){
		$fin_start_date = date("m-Y", strtotime($fin_result[0]->start_date));
		$month_tax_qry  = 'select process_month,monthly_tds from cw_transactions where employee_code="'.$emp_code.'" and trans_status=1 and transactions_month between "'.$fin_start_date.'" and "'.$process_month.'"';
		$month_tax_data   		= $this->db->query("CALL sp_a_run ('SELECT','$month_tax_qry')");
		$month_tax_rslt 	    = $month_tax_data->result_array();
		$month_tax_data->next_result();
		foreach($tax_col_arr as $key => $val){
			$rslt = $val[$emp_code];
			foreach($rslt as $label_name => $value){
				$replace_val  = '@'. $label_name.'@';
				$replace_value = $value; 
				if(empty($replace_value)){
					$replace_value ="0.00";
				}
				$print_design = str_replace($replace_val,$replace_value,$print_design);
			}
		}
		if($month_tax_rslt){
			$tr_line    = "";
			foreach($month_tax_rslt as $key => $value){
				$month        = $value['process_month'];
				$date         = DateTime::createFromFormat('m-Y', $month);
				$month_year   = $date->format('F Y');
				$month_tds    = $vale['monthly_tds'];
				if (empty($month_tds)) {
					$month_tds = "0.00";
				}
				$tot_val     +=$month_tds;
				$tr_line     .= "<tr><td>$month_year</td><td>$month_tds</td></tr>";
			}
			$table_line       ="<table><tr><td style='font-weight:bold;'>Tax Deducted So far</td></tr>$tr_line<tr><td style='font-weight:bold; font-size:12px;'>Total</td><td style='font-weight:bold; font-size:12px;'>$tot_val</td></tr></table>";
			$print_design = str_replace('@tax_month@',$table_line,$print_design);
		}
		$data_val       = "";
		foreach($leave_bal_arr as $key => $value){
			$bal_rslt   = $value[$emp_code];
			if($bal_rslt){
				$cl         = $bal_rslt['balance_cl'];
				$el         = $bal_rslt['balance_el'];
				$compnl     = $bal_rslt['balance_compnl'];
				$echl       = $bal_rslt['balance_echl'];
				$mal        = $bal_rslt['balance_mal'];
				$pl         = $bal_rslt['balance_pl'];
				$sl         = $bal_rslt['balance_sl'];
				$data_val   = "<div style='font-size:11px;'><span style='font-weight:bold;'>CL :</span><span> $cl</span>&nbsp;&nbsp;<span style='font-weight:bold;'>EL :</span><span> $el</span>&nbsp;&nbsp;<span style='font-weight:bold;'>COMPNL :</span><span> $compnl</span>&nbsp;&nbsp;<span>ECHL :</span><span> $echl</span>&nbsp;&nbsp;<span style='font-weight:bold;'>MAL :</span><span> $mal</span>&nbsp;&nbsp;<span style='font-weight:bold;'>PL :</span><span> $pl</span>&nbsp;&nbsp;<span style='font-weight:bold;'>SL :</span><span> $sl</span></div>";
				$print_design = str_replace('@leave_balance@',$data_val,$print_design);
			}
			
		}
		
		return $print_design;
	}

	//FUNCTION FOR HOLD FANDF EMPLOYEES (FINAL PAYSLIP)
	public function fandf_hold_payslip($print_design,$emp_code,$process_month,$form_rslt,$fandf_emp_result){	
		$dom = new \DOMDocument();
		$dom->loadHTML($print_design);
		$xpath = new \DOMXPath($dom);
	     
		//-----------------HEADER START--------------------//
		$month_data = array_values($fandf_emp_result[$emp_code] ?? []);
		$head_trs = $xpath->query("//table[@id='earnings']/thead/tr");
		foreach ($head_trs as $hrow) {
			$ths = $hrow->getElementsByTagName('th');
			$x = 0;
			foreach ($month_data[0] as $key => $value) {
				if ($x === 0) {
					$ths->item(1)->nodeValue = $key;
					$style = $ths->item(1)->getAttribute('style');
				} else {
					$th = $dom->createElement('th');
					$th->setAttribute('style', $style);
					// $th->setAttribute('style',"border:1px solid black;");
					$th->nodeValue = $key;
					$hrow->insertBefore($th, $ths->item($x + 1));
				}
				$x++;
			}
			// $th_total = $dom->createElement('td');
			// $th_total->nodeValue = "Total";
			// $hrow->appendChild($th_total);
		}		
		//-----------------HEADER END--------------------//
        //-------------------------EARNING TABLE START----------------------//
		$trs = $xpath->query("//table[@id='earnings']/tbody/tr");
		foreach ($trs as $row) {
			$tds = $row->getElementsByTagName('td');
			if ($tds->length > 1) {
				$view_name = $tds->item(0)->nodeValue;
				$lable_name = str_replace("@","", $tds->item(1)->nodeValue);
				$month_data = $fandf_emp_result[$emp_code][$lable_name];
				$x = 1;
				$earn_td_sum = 0;
				foreach ($month_data as $key => $value) {
					$earn_td_sum += $value;
					if ($x === 1) {						
						$tds->item($x)->nodeValue = $value;
						$style = $tds->item($x)->getAttribute('style');
					} else {
						$td = $dom->createElement('td');
						$td->setAttribute('style', $style);
						$td->nodeValue = $value;
						$row->insertBefore($td, $tds->item($x));
						if($lable_name === "total_earnings"){
							$td->setAttribute('style',"border-top:1px solid black;");
						}
					}
					$x++;
				}
				$tds->item($x)->nodeValue = $earn_td_sum;
			}
		}
		$saved_html = preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $dom->saveHTML());
		//-------------------------EARNING TABLE END----------------------//

	  //--------------------------DEDUCTION TABLE START-----------------//
		$trs = $xpath->query("//table[@id='deductions']/tbody/tr");
		$final_ear_tr = $trs->length;
		foreach ($trs as $row) {
			$tds       = $row->getElementsByTagName('td');
			$td_length = $tds->length;
			$td_tot    = 0;
			if ($tds->length > 1) {
				$view_name = $tds->item(0)->nodeValue;
				$lable_name = str_replace("@", "", $tds->item(1)->nodeValue);
				$month_data = $fandf_emp_result[$emp_code][$lable_name];
				$x      = 1;		
				$td_tot = 0;		
				foreach ($month_data as $key => $value) {
					$td_tot += $value;
					if ($x === 1) {
						$tds->item($x)->nodeValue = $value;
						$style = $tds->item($x)->getAttribute('style');
					}else{
						$td = $dom->createElement('td');
						$td->setAttribute('style', $style);
						if($lable_name === "total_deductions" || $lable_name === "net_pay"){
							$td->setAttribute('style',"border-top:1px solid black;");
						}					
						$td->nodeValue = $value;
						$row->insertBefore($td, $tds->item($x));											
					}
					$x++;
				}
				$tds->item($x)->nodeValue = $td_tot;
			}
		}
           //---------------DEDUCTION TABLE END---------------//
		   $salary_words = $this->numbertowords($td_tot);
		$saved_html = preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $dom->saveHTML());
		$print_rslt = str_replace(" @net_pay_words@ ONLY",$salary_words,$saved_html);
		return $print_rslt; 
	}

	public function multi_fandf_month($emp_stop_rslt,$emp_stop_count,$print_design_value){
		$dom 	    = new DOMDocument;
		$dom->loadHTML($print_design_value);
		for($i = 1; $emp_stop_count >= $i; $i++){
			$tbl 	      = $dom->getElementById('ear_tab_0');
			$tbl_dom 	  = new DOMDocument;
			$tbl_dom->loadHTML($tbl);
			$tbl_dom->getElementsByTagName('table')->item(0)->removeAttribute('id');
			$tbl_dom->getElementsByTagName('table')->item(0)->setAttribute('id', 'ear_tab_1');		
			$tabl_clone = $dom->importNode($tbl, TRUE);
			$tbl->parentNode->appendChild($tabl_clone);
			// $dom->importNode($tbl, TRUE);
			// foreach($tbls as $tbl) {		
			// 	$id 	= $tbl->getAttribute("id");
			//     $tbl->nodeValue = $table_key[$id];
			// }
		}
		echo "Hello".$dom->saveHTML();
		
		// die;
		// $srcDoc->loadXML( $srcXML );
		// $destDoc->loadXML( $destXML );
		// $destNode = $destDoc->getElementsByTagName('repository')->item( 0 );
		// $srcNode  = $srcDoc->getElementsByTagName('repository')->item( 0 );
		// $import   = $destDoc->importNode($srcNode, TRUE);
		// $destNode->parentNode->appendChild($import);
		// echo $destDoc->saveXML();
	}

	public function get_pdf($design_name,$pdf_paper_size,$pdf_sheet_type,$pdf_set_password,$pdf_sheet_per_page,$print_id,$content,$column_name,$payslip_month,$emp_code,$process_by,$folder_tbl_name,$cate_name,$process_month,$suppressed_data,$payslip_based_on,$pwd_column){
		$design_name 	= str_replace(' ', '_', $design_name);
		$cate_name 		= str_replace(' ', '_', $cate_name);
		$folder_tbl_name= str_replace(' ', '_', $folder_tbl_name);
		$folder 	= 'pdf_generation/'.$folder_tbl_name."/$design_name/$process_month/".$payslip_based_on."_".$cate_name;
		$file_type 	= ".pdf";
		$path 		= $this->generate_pdf_bulk($content,$folder,$emp_code,$pdf_sheet_type,$pdf_paper_size,$pdf_set_password,$file_type,$process_by,$suppressed_data,$pwd_column);
		return $path;
	}
	public function load_all_data($block_result,$print_table_result,$form_result_array,$where_result_arr,$split_result_arr,$where_month_col,$process_month,$in_empcode,$payslip_based_on){
		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'];
			$folder_column    	   = $block['folder_column'];
			$table_rslt            = $print_table_result[$prime_print_block_id];
			$line_table_query      = "";
			foreach($table_rslt as $table_result){
				$line_prime_table = $table_result['line_prime_table'];
				$line_prime_col   = $table_result['line_prime_col'];
				$line_join_type   = $table_result['line_join_type'];
				$line_join_table  = $table_result['line_join_table'];
				$line_join_col    = $table_result['line_join_col'];
				$line_sort        = $table_result['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 = "";
				if($folder_column){
					$select_query.= "$folder_column as folder_column_name,";
				}
				$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_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($label_name){
							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_rslt 	= $where_result_arr[$prime_print_block_id];
			if(!empty($where_rslt)){
				$where_condition = str_replace('^','"',$where_rslt['where_condition']);
				$where_condition = str_replace('@logged_id@',$emp_id,$where_condition);
				$where_condition = str_replace('@input_month@',$payslip_month,$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));
			// 	$select_ytd_query = rtrim($select_ytd_query,',');
			// 	$select_ytd_query = rtrim($select_ytd_query,' , ');
			// 	$where_ytd_condition  = ' and cw_transactions.employee_code="'.$emp_code.'" 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("'.$payslip_month.'", "%m-%Y"), "%Y-%m")';
			// 	$final_ytd_qry = "select $select_ytd_query from $line_table_query $pick_query  where $where_trans $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 $where_trans $where_condition $where_month_col";
			$tr_line = "";
			$th_line = "";
			$count = 0;
			$assign_date_formate_list  = array("DMY"=>"d-m-Y","YMD"=>"Y-m-d","MY"=>"F-Y","YM"=>"Y-F","D"=>"d","M"=>"M","Y"=>"Y");
			$split_array  = array();
			$split_result = $split_result_arr[$print_id];
			foreach($split_result as $split){
				$split_info  = $split->split_info;
				$split_colum = $split->split_colum;
				$split_array[$split_colum] = $split_info;
			}	
		}
		$map_column = explode(",",$print_block_column);
		$final_qry_array = array('final_qry'=>$final_qry,'split_array'=>$split_array,'map_column'=>$map_column,'print_design'=>$print_design,'assign_date_formate_list'=>$assign_date_formate_list,'block_result'=>$block_result);
		return $final_qry_array;
	}
	public function generate_pdf_bulk($table_data,$folder,$file_name,$set_paper,$paper_size,$pdf_set_password,$file_type,$process_by,$suppressed_data,$pwd_column){
		$folder = strtolower($folder);
		if((int)$suppressed_data === 1){
			// THIS IS ENABLE TAMIL CONTENT ON PDF SUPPRESSEDDATA IS 1 DON"T REMOVE
			// libxml_use_internal_errors(true); // Suppress parsing warnings
			// $table_data_utf8 = '<?xml encoding="UTF-8">' . $table_data;
			// $dom             = new \DOMDocument('1.0', 'UTF-8');
			// $dom->loadHTML($table_data_utf8);
			$dom     = new \DOMDocument();
			$dom->loadHTML($table_data);
			$xpath   = new \DOMXPath($dom);

			# EARNINGS	
			$earn_ct = 0;
			$trs     = $xpath->query("//table[@id='earnings']/tbody/tr");	
			foreach($trs as $row){
				$tds       = $row->getElementsByTagName('td');				
			    $lastIndex = $tds->length - 1; // Index of the last column		
			    if($tds->item($lastIndex)->nodeValue !== '0.00' && $tds->item($lastIndex)->nodeValue !== ''){
			        $earn_ct++;
			    }				
				for($i = 0; $i <= $tds->length; $i++){
					if($tds->item($i)->nodeValue === '0.00' ){
						if($row->parentNode){
							$row->parentNode->removeChild($row);
							break;
						}					
					}
			    }
				$allEmpty = true;
				for($i = 0; $i < $tds->length; $i++){
				    if($tds->item($i)->nodeValue !== ''){
				        $allEmpty = false;
				        break;
				    }
				}
				if($allEmpty && $row->parentNode){
				    // If all values are empty, remove the parent node
				    $row->parentNode->removeChild($row);
				}
			}
			# DEDUCTIONS
			$ded_ct  = 0;
			$trs_ded = $xpath->query("//table[@id='deductions']/tbody/tr");
			foreach($trs_ded as $row_ded){
				$tds_ded   = $row_ded->getElementsByTagName('td');
			    $lastIndex = $tds_ded->length - 1; // Index of the last column
				if($tds_ded->item($lastIndex)->nodeValue !== '0.00' && $tds_ded->item($lastIndex)->nodeValue !== ''){
			        $ded_ct++;
			    }
				for($i = 0; $i <= $tds_ded->length; $i++){
					if($tds_ded->item($i)->nodeValue === '0.00' ){
						if($row_ded->parentNode){ 
							$row_ded->parentNode->removeChild($row_ded);
							break;
						}						
					}
			    }
				$Empty = true;
				for($i = 0; $i < $tds_ded->length; $i++){
				    if($tds_ded->item($i)->nodeValue !== ''){
				        $Empty = false;
				        break;
				    }
				}
				if($Empty && $row_ded->parentNode){
				    // If all values are empty, remove the parent node
				    $row_ded->parentNode->removeChild($row_ded);
				}	   
			}
			# ADD COLUMNS TO BALANCE STYLE PURPOSE
			if($earn_ct > $ded_ct){	
				$trs_ded_app    = $xpath->query("//table[@id='deductions']/tbody/tr");
			    $difference     = abs($ded_ct - $earn_ct);
			    $last_row_index = $trs_ded_app->length - 1;
    			$last_row       = $trs_ded_app->item($last_row_index);
		        for($i = 0; $i < $difference; $i++){ #CREATE NEW ROW
		        	$z = 0;
				    $new_row    = $dom->createElement('tr');
					if($last_row){
						$cols       = $last_row->getElementsByTagName('td'); 
						foreach($cols as $col){
							$empty_cell = $dom->createElement('td');
							$style      = $last_row->childNodes->item($z)->getAttribute('style');
							$empty_cell->setAttribute('style', $style);
							$new_row->appendChild($empty_cell);
							$z++;
						}
						$last_row_parent = $last_row->parentNode;
						$last_row_parent->appendChild($new_row);
					}
				}
			}else
			if($ded_ct > $earn_ct){
			    $trs_ear_app    = $xpath->query("//table[@id='earnings']/tbody/tr");
			    $difference     = abs($ded_ct - $earn_ct);
			    $last_row_index = $trs_ear_app->length - 1;
    			$last_row       = $trs_ear_app->item($last_row_index);
		        for($i = 0; $i < $difference; $i++){ #CREATE NEW ROW
		        	$j = 0;
				    $new_row    = $dom->createElement('tr');
					if($last_row){
						$cols       = $last_row->getElementsByTagName('td');
						foreach($cols as $col){
							$empty_cell = $dom->createElement('td');
							$style      = $last_row->childNodes->item($j)->getAttribute('style');
							$empty_cell->setAttribute('style', $style);
							$new_row->appendChild($empty_cell);
							$j++;
						}
						$last_row_parent = $last_row->parentNode;
						$last_row_parent->appendChild($new_row);
					}			        		
			    }	
			}
			//For FandF Design 
			$xpath = new \DOMXPath($dom);
			//loop all <tr> element.
			foreach($xpath->query('//tr') as $tr){
			    $tds = $tr->getElementsByTagName('td');
				if($tds){
					for($i = 0; $i <= $tr->length; $i++){
						// get table cell value.
						$table_cell_value = $tds->item($i)->nodeValue;
						if($table_cell_value === '0.00'){
							$tr->parentNode->removeChild($tr);
							break; 
						} 
					}
				}		   		
			}
			// get the result
			$saved_html = preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $dom->saveHTML());
			// THIS ALSO TAMIL FONT DECODE IN TAMIL CONTENT IN PDF
			// $saved_html = mb_convert_encoding($saved_html, 'UTF-8', 'HTML-ENTITIES');
		}else{
			$saved_html = $table_data;
		}
		$db_name        = $this->config->item("db_name");
		$server_name    = $_SERVER['HTTP_HOST'];//[MS 06-07-2024]
		if($server_name !== "localhost" && $server_name !== "rebaradcche" && $server_name !== "hrms.allyindian.com"){
			$table_data = str_replace("~",'"',$saved_html);
			$table_data = str_replace("`","'",$table_data);
			$table_data = str_replace("^","&",$table_data);
			//PATH CREATION TO STORE THE FILES 
			$oldmask    = umask(0);
			if(!file_exists($folder)){
				mkdir($folder, 0777, true); # IF NOT CREATE
			}
			//FILE WRITE AS HTML
			file_put_contents($folder."/".$file_name.".html" , $table_data);
			chmod($folder."/".$file_name.".html", 0777);
			umask($oldmask);
			$directory      = str_replace('application/controllers', '', __DIR__);
			$html_file_name = $directory.$folder."/".$file_name.".html";	
			$pdf_file_name  = $directory.$folder."/".$file_name.".pdf";
			
			if(file_exists($html_file_name)){
				//CONVERT HTML FILE TO PDF 
				$command    = "xvfb-run  wkhtmltopdf --orientation $set_paper --page-size $paper_size $html_file_name $pdf_file_name";
				$output     = shell_exec($command);
				unlink($html_file_name);
				$path       = $pdf_file_name;
			}
		}else{
			// THIS SECTION OF CODE TAMIL FONT ENABLE IN PDF GENERATION CODE DON"T REMOVE
		// 	$table_data = str_replace("~",'"',$saved_html);
		// 	$table_data = str_replace("`","'",$table_data);
		// 	$table_data = str_replace("^","&",$table_data);
		// 	// Clean HTML content
		// 	$wkpath = APPPATH . 'libraries/wkhtmltopdf/bin/wkhtmltopdf.exe';
		// 	$wkpath = str_replace('\\', '/', $wkpath);
		// 	// Define file paths
		// 	$html_file_name = $folder . "/" . $file_name . ".html";
		// 	$pdf_file_name  = $folder . "/" . $file_name . ".pdf";

		// 	// Create folder if not exists
		// 	if(!file_exists($folder)) {
		// 		mkdir($folder, 0755, true);
		// 	}

		// 	// Save HTML to temp file
		// 	file_put_contents($html_file_name, $table_data);
		// 	chmod($html_file_name, 0644);

		// 	// Paper size and orientation
		// 	$pageSizeOption    = "--page-size " . escapeshellarg($paper_size);
		// 	$orientationOption = "--orientation " . escapeshellarg(ucfirst($set_paper));

		// 	// // Build the wkhtmltopdf command (NO password if unsupported)
		// 	$command = sprintf(
		// 		'%s --enable-local-file-access --no-pdf-compression --encoding UTF-8 --quiet ' .
		// 		'--no-print-media-type --disable-smart-shrinking --margin-top 20mm --margin-bottom 20mm ' .
		// 		'--margin-left 20mm --margin-right 20mm %s %s %s %s',
		// 		escapeshellcmd($wkpath),
		// 		$pageSizeOption,
		// 		$orientationOption,
		// 		escapeshellarg($html_file_name),
		// 		escapeshellarg($pdf_file_name)
		// 	);
		// 	// Execute the command
		// 	exec($command, $output, $return_var);
		// 	// Clean up temp file
		// 	if(file_exists($html_file_name)){
		// 		unlink($html_file_name);
		// 	}
		// 	// Set PDF permissions
		// 	if(file_exists($pdf_file_name)){
		// 		chmod($pdf_file_name, 0755);
		// 	}
		// 	$path = $pdf_file_name;
			$path = $this->common_generate_pdf($saved_html,$folder,$file_name,$set_paper,$paper_size,$pdf_set_password,$pwd_column);
		}
		return $path;
	}
	    public function download_zip(){
         //Encryption
		$encString      = file_get_contents('php://input');
		$_POST          = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$encString         = file_get_contents('php://input');
		$_POST             = $this->cryptoDecrypt($encString);
		if(!$_POST){
			echo json_encode(array('success' => false,'message' => 'Invalid Request..','table_data' => ""));
			exit(0);
		}
		$emp_codes 		= $this->input->post("emp_codes");
		$emp_codes  	= str_replace('"', '', $emp_codes);
		$emp_code_arr  	= explode(',', $emp_codes);
		$path_name  	= strtolower($this->input->post('path_name'));
		$path       	= "./pdf_generation/".$path_name."/";
		$zip        	= new ZipArchive();
		$filename   	= "./pdf_generation/".$path_name.".zip";
		unlink($filename);
		if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
			exit("cannot open <$filename>\n");
		}
		$dir = $path;
		if (is_dir($dir)){
			if ($dh = opendir($dir)){
				while (($file = readdir($dh)) !== false){
					if($file != '' && $file != '.' && $file != '..'){
						$file_name = $path.$file.'/';
						if (is_dir($file_name)){
							if ($dhs = opendir($file_name)){
								while (($files = readdir($dhs)) !== false){
									if (in_array($files, $emp_code_arr)){
										if (is_file($file_name.$files)) {
											if($files != '' && $files != '.' && $files != '..'){
												$zip->addFile($file_name.$files);
											}
										}
									}
								}
								closedir($dhs);
							}
						}
					}
				}
				closedir($dh);
			}
		}
		$zip->close();
		$filename  = str_replace("./","",$filename);
		echo json_encode(array('success' => true,'filename' => $filename));
	}
	public function view_emp_details($emp_codes_array,$process_by,$process_mode,$folder_arr,$column_name,$emp_rslt,$dw_all,$tbl_name,$folder_tbl_name,$design_name,$process_month,$encrypted_pdf,$pdf_type){
		if($design_name === "form_wr"){//THIS CONDITION FOR ONLY ONE ROW FOR WAGE REGISTER
			$emp_codes_array = array_keys($folder_arr);
		}
		$db_name           = $this->config->item("db_name");
		$payslip_based_on  = $this->company_info();
		$payslip_based_on  = $payslip_based_on[0]->payslip_based_on;
		if($pdf_type === 1){
			$tble_line     = "";
			$count         = 0;
			foreach($emp_codes_array as $key => $emp_code){
				if($process_mode === 1){
					$folder_name 	   = $folder_arr[$emp_code];
					$emp_name 		   = $emp_rslt[$count]['emp_name'];
				}else
				if($process_mode === 2){
					$cate_name 	       = $folder_arr[$emp_code]['payslip_based_desc'];
					$design_name 	   = str_replace(' ', '_', $design_name);
					$cate_name 		   = str_replace(' ', '_', $cate_name);
					$folder_tbl_name   = str_replace(' ', '_', $folder_tbl_name);
					$folder_name 	   = 'pdf_generation/'.$folder_tbl_name."/".$design_name."/".$process_month."/".$payslip_based_on."_".$cate_name;
					$emp_name 		   = $folder_arr[$emp_code]['emp_name'];
				}
				$folder_name 	       = strtolower(str_replace(' ', '_', $folder_name));
				$payslip_month         = date('m-Y', strtotime($process_month));
				if((int)$encrypted_pdf === 1){		
					if($pdf_type === 1){
						$file_name     = $db_name."_".$emp_code."_".$process_month; 
						$enc_file      = $this->encryptFilename($file_name,$db_name);	
						$enc_file_name =  $enc_file."_".$emp_code;
					}
				}else{
					$enc_file_name     = $emp_code;
				}	
				$file_path             = $folder_name."/".$enc_file_name.".pdf";
				$exist_file 	       = './'.$folder_name."/".$enc_file_name.".pdf";
				$exist_process 	       = true;  
				//if($process_mode === 2){
					if(file_exists($exist_file)){
						$exist_process = true;
					}else{
						$exist_process = false;
					}
				//}
				$filename = dirname(__FILE__).$file_path;
				$filename = str_replace("application\controllers","",$filename);
				if($exist_process){
					$file_path  = base_url().$file_path;	
					$enc_path   = base64_encode($file_path);
					if($design_name === "form_wr"){//[MS 08-07-2024]
						$tble_line .= "	<tr class='gradeU'><td>1.</td><td>Wage Register PDF</td><td><a class='btn btn-primary btn-sm' style='margin-right:5px;' onclick=pdf_viewer('$enc_path')><span class='fa fa-eye' >&nbsp;</span> view </a><a class='btn btn-primary btn-sm' onclick=download_payslip('download_$emp_code','$enc_path') id='download_$emp_code' download '><span class='fa fa-download' download>&nbsp;</span> Download </a></td></tr>";
					}else{
						$tble_line .= "	<tr class='gradeU'><td>$emp_code</td><td>$emp_name</td><td><a class='btn btn-primary btn-sm' style='margin-right:5px;' onclick=pdf_viewer('$enc_path')><span class='fa fa-eye' >&nbsp;</span> view </a><a class='btn btn-primary btn-sm' onclick=download_payslip('download_$emp_code','$enc_path') id='download_$emp_code' download '><span class='fa fa-download' download>&nbsp;</span> Download </a></td></tr>";
					}
				}
				$count++;
			}
			if($emp_codes_array){
				foreach($emp_codes_array as $key => $value){
					if((int)$encrypted_pdf === 1){
						// MS [11-07-2024]
						$file_name     = $db_name."_".$value."_".$process_month; 
						$enc_file      = $this->encryptFilename($file_name,$db_name);	
	        			$enc_file_name = $enc_file . "_" . $value;
						$emp_code_arr[$key] = $enc_file_name;
					}else{
						$emp_code_arr[$key] = $value;
					}	
				}
				$emp_codes_arr_val = '"'.implode('.pdf","', $emp_code_arr ?? []).'.pdf"';
			}
			$tfoot_list = "<tfoot><tr class='gradeU'><td></td><td style='text-align:center;'><a class='btn btn-primary btn-sm' onclick = download_zip('$dw_all','$emp_codes_arr_val') ><span class='fa fa-download' >&nbsp;</span> Download All </a></td><td></td></tr>
				</tfoot>";
			if($design_name === "form_wr"){//[MS 08-07-2024]
				$table_data = "<table class='table table-striped table-bordered' id='emp_details'><thead><tr><th>SNO</th><th>PDF Name</th><th>Action</th></tr></thead><tbody>$tble_line</tbody>$tfoot_list</table>";
			}else{
				$table_data = "<table class='table table-striped table-bordered' id='emp_details'><thead><tr><th>Employee Code</th><th>Employee Name</th><th>Action</th></tr></thead><tbody>$tble_line</tbody>$tfoot_list</table>";
			}
		}else{
			$tble_line      = '';
			//COMBINE TABLE VIEW 
			if($process_mode === 1){ //GENERATE
				$column_array   = array();
				foreach($folder_arr as $val){
					$folder     = $val['folder'];
					$file_name  = $val['file_name'];
					$file_path  = base_url().$folder."/".$file_name.".pdf";
					$enc_path   = base64_encode($file_path);
					$cate_name  = strtoupper(str_replace('_', ' ', $val['cate_name']));
					$tble_line .= "<tr class='gradeU'><td>$cate_name</td><td><a class='btn btn-primary btn-sm' onclick = pdf_viewer('$enc_path')><span class='fa fa-eye' >&nbsp;</span> view </a></td></tr>";
					$column_array[] = $val['file_name'];
				}
			}else{ //VIEW
				$column_array   = array();
				foreach($folder_arr as $combine){
					$combine_id        = $combine[$payslip_based_on];
					$combine_desc      = strtolower(str_replace(' ', '_', $combine['payslip_based_desc']));
					$payslip_month     = date('m-Y', strtotime($process_month));
					if((int)$encrypted_pdf === 1){		
						$file_name     = $db_name."_".$combine_id."_".$process_month; 
						$enc_file      = $this->encryptFilename($file_name,$db_name);	
						$enc_file_name =  $enc_file."_".$combine_desc;
					}else{
						$enc_file_name = $combine_desc;
					}
					$folder_name 	   = 'pdf_generation/'.$folder_tbl_name."/".$design_name."/".$process_month."/".$payslip_based_on."_".$combine_desc;
					$file_path         = $folder_name."/".$enc_file_name.".pdf";
					$exist_file 	   = './'.$folder_name."/".$enc_file_name.".pdf";
					if(file_exists($exist_file)){
						$enc_path      = base64_encode($file_path);
						$tble_line    .= "<tr class='gradeU'><td>{$combine['payslip_based_desc']}</td><td><a class='btn btn-primary btn-sm' onclick = pdf_viewer('$enc_path')><span class='fa fa-eye' >&nbsp;</span> view </a></td></tr>";
						$column_array[] = $enc_file_name;
					}
				}
			}			
			if($column_array){ //DOWNLOAD ALL
				$column_array_val  = '"'.implode('.pdf","', $column_array ?? []).'.pdf"';
				$column_array_val  = str_replace('/', '_',$column_array_val);
				$tfoot_list        = "<tfoot><tr class='gradeU'><td style='text-align:center;'><a class='btn btn-primary btn-sm' onclick = download_zip('$dw_all','$column_array_val') ><span class='fa fa-download' >&nbsp;</span> Download All </a></td><td></td></tr></tfoot>";
			}
			$table_data = "<table class='table table-striped table-bordered' id='emp_details'><thead><tr><th>Column</th><th>Action</th></tr></thead><tbody>$tble_line</tbody>$tfoot_list</table>";
		}
		return $table_data;
	}
	//Increment Replace Current and New value
	public function increment_replace($print_design,$inc_arr){
		foreach ($inc_arr as $key => $value) {
			$current_value = $value['current_value'];
			$new_value     = $value['new_value'];
			$current_col   = "@current_$key@";
			$new_col       = "@new_$key@";
			$current_wcol  = "@current_".$key."_words@";
			$new_wcol      = "@new_".$key."_words@";
			$current_words = $this->numbertowords($current_value);
			$new_words     = $this->numbertowords($new_value);
			$print_design  = str_replace($current_col,$current_value,$print_design);
			$print_design  = str_replace($new_col,$new_value,$print_design);	
			$print_design  = str_replace($current_wcol,$current_words,$print_design);
			$print_design  = str_replace($new_wcol,$new_words,$print_design);		
		}		
		return $print_design;
	}
}