MOON
Server: Apache
System: Linux nserver.cafsindia.com 4.18.0-553.104.1.lve.el8.x86_64 #1 SMP Tue Feb 10 20:07:30 UTC 2026 x86_64
User: cafsindia (1002)
PHP: 8.2.30
Disabled: NONE
Upload Files
File: /home/cafsindia/uds.cafsinfotech.in/app/api_model.php
<?php
error_reporting(0);
date_default_timezone_set('Asia/Kolkata');
include('./dbconnect.php');
require('../phpmailer/class.phpmailer.php');
require('../application/libraries/dompdf/autoload.inc.php');
require ('../application/libraries/PDFMerger.php'); 
use PDFMerger\PDFMerger; 
use Dompdf\Dompdf;
class api_model extends dbconnect{	
	protected $app_url;
	private $enckey              = 'vDIa5JdknBqfrKOu8d7UpddnBMCH1vza'; //32 characters
	public function __construct(){
		$this->open_db();
		$this->$app_url			 = 'http://122.186.126.218:8030/adminapp/api';
		$get_email_qry           = 'select * from cw_mail_configurations where trans_status = 1 and mail_status = 1';
		$email_info              = $this->runQuery("$get_email_qry");
		$email_result            = $this->result($email_info);
		if($email_result){
			$this->smtp_server   = $email_result[0]->smtp_server;
			$this->port_no       = $email_result[0]->port_no;
			$this->user_name     = $email_result[0]->mail_username;
			$this->user_password = $email_result[0]->mail_password;
			$this->hr_mail       = $email_result[0]->sender_email;
			$this->cc_mail       = $email_result[0]->bcc;
			$this->sender_name   = $email_result[0]->sender_name;
		}
    }
	//check data
	public function is_exit_data($exit_qry){
		$exit_info     = $this->runQuery("$exit_qry");
		$exit_result   = $this->result($exit_info);
		mysqli_next_result($this->db);		
		return $exit_result;
	}
	public function is_exit_array($exit_qry){
		$exit_result   = array();
		$exit_info     = $this->runQuery("$exit_qry");
		if($exit_info){
	        while($row = mysqli_fetch_assoc($exit_info)){
	            $exit_result[] = $row;
	        }
		}
		mysqli_next_result($this->db);		
		return $exit_result;
	}
	//Process Payroll scheduller update
	public function payroll_proced($project_id,$wbs_element,$process_month,$prime_id){
		$mysql_info    = $this->runQuery("CALL itsp_project_prcpay('$project_id','$wbs_element','$process_month','$prime_id')");
		$mysql_result  = $this->result($mysql_info);
		mysqli_next_result($this->db);
		$mysql_result  = json_decode(json_encode($mysql_result),true);
		return $mysql_result;
	}
	//INSERT AND UPDATE QRY FUCNTION 
	public function pay_qry_process($prime_query){
		$qry_info     = $this->runQuery("$prime_query");
		if($qry_info){
			return true;
		}
	}
	//PDF GENERATION
	public function pdf_generation_common($project_id,$wbs_element,$employee_code,$process_month,$pdf_template,$module_name,$db_name,$print_table_result,$where_result,$form_result_array,$form_set_rslt,$design_arr,$payslip_based_on,$payslip_arr,$prime_id){
		//PRINT INFO
		$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_result       =  $this->is_exit_array($block_qry);
		$print_id           = $block_result[0]['prime_print_info_id'];	
		$print_design_value = $design_arr[$print_id];
		$print_design_value = str_replace('~','"',$print_design_value);
		$design_name        = strtolower(str_replace(' ', '_', $block_result[0]['print_block_name']));
		$password_column    = $block_result[0]['password_column'];
		$emp_codes_array    = array_filter($employee_code);
		$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,$form_set_rslt); 
		//WHERE CONDITION
		$where_month_col    = ' '.$where_column.' and cw_transactions_fms.'.$payslip_based_on.'
		 = "'.$wbs_element.'" and cw_employees.employee_code in("'.$in_empcode.'")';
		//FUNCTION LOAD DATA
		$final_qry_array    = $this->load_all_data($block_result,$print_table_result,$form_result_array,$where_result,$where_month_col,$process_month,$in_empcode,$payslip_based_on);
		$final_qry 		    = $final_qry_array['final_qry'];
		$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_result   = $this->is_exit_data($final_qry);
		$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';
			if($final_qry_result){
				$data['print_sts']         = true;
				$emp_detail_arr            = array();
				$emp_data_arr 	           = array();
				$final_data_rslt           = array();
				$count = 0;
				foreach($final_qry_result as $rslt){
					$payslip_rules         = $rslt->payslip_rules;
					$payslip_form          = $rslt->payslip_form_no;
					$count++;
					$map_column            = explode(",",$print_block_column);
					$td_line               = "";					
					$print_design          = $print_design_value;
					foreach($map_column as $table_column){	
						$map_column        = explode(".",$table_column);
						$column 	       = $map_column[1];
						$value             = $rslt->$column;
						$replace_val       = "@".$column."@";
						if($column == 'net_pay'){
							$value         = $rslt->$column;
							$value         = $value;
							$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);
						//FOR PAYSLIP FORM AND RULES STATIC CODE
						$print_design      = str_replace("@payslip_rules@",$payslip_rules,$print_design);
						$print_design      = str_replace("@payslip_form@",$payslip_form,$print_design);
						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' || $column == 'process_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));
							if(($value === "") || ($value === "0.00") || ($value === "0") || (!$value)){
								$th_line = "";
							}else{
								$th_line.= "<th style='text-align:center;'>$head_name</th>";
							}
						}
						if($column === 'employee_code'){
							$emp_code = $value;
						}else
						if($column === 'folder_column_name'){
							$payslip_based_id = strtolower(str_replace(" ", "_", $value));
							$payslip_wbs_desc = strtolower(str_replace(" ", "_", $payslip_arr[$value]));
						}
					}
					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>";
							}
						}
					}
					$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_wbs_desc']  = $payslip_wbs_desc;
					$emp_data_arr[$payslip_based_id][$emp_code]['print_design'] 	 = $print_design;
				}
			}
		}
		return $this->single_pdf($emp_data_arr,$design_name,$payslip_based_on,$folder_tbl_name,$process_month,$db_name,$prime_id);
	}
	//SINGLE SHEET PDF GENERATION
	public function single_pdf($emp_data_arr,$design_name,$payslip_based_on,$folder_tbl_name,$process_month,$db_name,$prime_id){
		$get_pdf_design  = "";
		$folder_arr      = array();
		$processed_count = 0;
		$failed_count    = 0;
		foreach($emp_data_arr as $based_on => $emp_data){
			foreach($emp_data as $key => $emp_detail){
				$emp_code 		= $emp_detail['emp_code'];
				$file_name      = $db_name."_".$emp_code; 
				$enc_file       = base64_encode($file_name);
				$enc_file_name  =  $enc_file."_".$emp_code;
				$enc_file_name  = $this->encryptFilename($enc_file_name,$db_name);
				$enc_file_name  = $enc_file_name."_".$emp_code;
				$cate_name 		= str_replace('/', '_',strtolower(str_replace(' ', '_', $emp_detail['payslip_based_id'])));
				$wbs_desc 		= str_replace('/', '_',strtolower(str_replace(' ', '_', $emp_detail['payslip_wbs_desc'])));
				$wbs_desc       = preg_replace('/[^A-Za-z]/', '_', $wbs_desc);
				$print_design 	= $emp_detail['print_design'];
				$print_design   = str_replace('~', '"', $print_design);
				$print_design   = "<!DOCTYPE html><head></head><style>table{border-collapse: collapse;}table td.fr-highlighted,.fr-view table th.fr-highlighted{border:1px solid black !important;vertical-align: text-top;}</style><body>".$print_design."</body></html>";
				$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."_".$wbs_desc;
				$folder_path 	= strtolower('pdf_generation/'.$folder_tbl_name."/$design_name/$process_month/".$payslip_based_on."_".$wbs_desc);
				//SUPPRESS DATA
				$folder         = strtolower($folder);
				$dom            = new \DOMDocument();
				$dom->loadHTML($print_design);
				$xpath          = new \DOMXPath($dom);
				//loop all <tr> element.
				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'){
							if($tr->parentNode){
								$tr->parentNode->removeChild($tr);
							}
						} 
				    }
				}
				// get the result
				$final_rslt = preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $dom->saveHTML());
				//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" , $final_rslt);
				chmod($folder."/".$enc_file_name.".html", 0777);
				umask($oldmask);
				$dw_all      	= $folder_tbl_name."/".$design_name."/".$process_month;
				$directory      = str_replace('app', '', __DIR__);
				$html_file_name = $directory.$folder_path."/".$enc_file_name.".html";	
				$pdf_file_name  = $directory.$folder_path."/".$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);
					unlink($html_file_name);
				}
				if(file_exists($pdf_file_name)){
					$processed_count++;
					$upd_qry    = 'UPDATE cw_transactions_fms SET payslip_sts = "1" WHERE prime_trans_process_id = "'.$prime_id.'" AND employee_code = "'.$emp_code.'"  ';
					$this->pay_qry_process($upd_qry);
				}else{
					$failed_count++;
					$upd_qry    = 'UPDATE cw_transactions_fms SET payslip_sts = "0" WHERE prime_trans_process_id = "'.$prime_id.'" AND employee_code = "'.$emp_code.'"  ';
					$this->pay_qry_process($upd_qry);
				}
			}	
		}	
		$final_array = ['processed_count' => $processed_count, 'failed_count' => $failed_count];
		return $final_array;
	}

	public function load_all_data($block_result,$print_table_result,$form_result_array,$where_result,$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     = "";
				$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 === "transactions_fms"){
						$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)){
								$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 ,";
				}
				if($trans_info === "cw_transactions_fms"){
					$select_query .= "cw_transactions_fms.transactions_month , ";
				}				
				$where_trans .= " $trans_info.trans_status = 1 and ";
			}
			$select_query .= "sap_personal_code.payslip_rules , sap_personal_code.payslip_form_no , ";
			$pick_query   .= "inner join cw_sap_personal_area as sap_personal_code on sap_personal_code.personal_code = cw_employees.personal_code ";
			$where_trans   = rtrim($where_trans,'and ');
			$where_rslt    = $where_result[$prime_print_block_id];
			$select_query = rtrim($select_query,',');
			$select_query = rtrim($select_query,' , ');
			$wher_cond = $where_rslt['where_condition'];
			$final_qry    = "select $select_query from $line_table_query $pick_query where $where_trans $where_month_col $wher_cond";
			$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");
		}
		$map_column       = explode(",",$print_block_column);
		$final_qry_array  = array('final_qry'=>$final_qry,'map_column'=>$map_column,'assign_date_formate_list'=>$assign_date_formate_list,'block_result'=>$block_result);
		return $final_qry_array;
	}

	public function where_month_value($module_name,$pdf_template,$process_month,$form_set_rslt){
		$month_col_qry    = '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_col_rslt   = $this->is_exit_data($month_col_qry);
		$where_month 	  = $month_col_rslt[0]->month_column;
		$where_table 	  = $month_col_rslt[0]->print_block_table;
		$module_name 	  = implode('","',explode(',', $where_table));
		$module_name 	  = str_replace('cw_', '', $module_name);
		$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_set_rslt[$label_name]['field_type'];
			$date_type    = $form_set_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;
	}
	//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;
	}

	//PDF Encrypted 
	public function encryptFilename($data,$key){
	    $method = 'aes-256-gcm'; 
	    $key    = base64_decode( $key );
	    $iv     =  openssl_cipher_iv_length( $method ) ;
	    $tag    = ""; // openssl_encrypt will fill this
	    $result = openssl_encrypt( $data , $method , $key , OPENSSL_RAW_DATA , $iv , $tag , "" , 6 );
	    $dirty  = array("+", "/", "=");
    	$clean  = array("_PLUS_", "_SLASH_", "_EQUALS_");
	    return str_replace($dirty, $clean,base64_encode($iv.$tag.$result ));
	}

	//START Cron Status
	public function insert_cron_status($source,$frm,$start,$process_type,$process_date){
		$query      = 'INSERT into cw_cron_status(cron_source,cron_for,cron_status,start_time,process_type,trans_created_date,process_date) values ("'.$source.'","'.$frm.'","Inprogress","'.$start.'","'.$process_type.'","'.date("Y-m-d H:i:s").'","'.$process_date.'")';
		$insert_id    = $this->runQuery_insert_id($query);
		mysqli_next_result($this->db);	
		return $insert_id;
	}

	//END Cron Status
	public function update_cron_status($prime_cron_id,$rslt){
		$end               = date("Y-m-d H:i:s"); 
		$cron_status       = "Success"; // Need to change
		$query           = 'UPDATE cw_cron_status SET count = "'.$rslt.'",end_time = "'.$end.'",cron_status = "'.$cron_status.'",trans_updated_date = "'.date("Y-m-d H:i:s").'"  WHERE prime_cron_status_id = "'.$prime_cron_id.'"';
		$mysql_info        = $this->runQuery("$query");
		mysqli_next_result($this->db);	
		return $mysql_info;
	}

	public function email_msg($msg){
		$content  = "<div><p>Dear team,</p><p style='margin-bottom: 20px;margin-left:30px'>".$msg.".</p><p>With Regards,<br/>HRMS Team.</p></div>";
		return $content;
	}

	public function call_email($msg){
		$smtp_server      = $this->smtp_server;  
		$port_no          = $this->port_no; 
		$user_name        = $this->user_name;  
		$user_password    = $this->user_password;  
		$hr_mail          = $this->hr_mail;  	
		$sender_name      = $this->sender_name;
		$cc_mail          = $this->cc_mail;
		$mail             = new PHPMailer();
		$mail->SMTPDebug  = 3;
		$mail->IsSMTP();
		$mail->Host       = $smtp_server;
		$mail->Port       = $port_no; 
		$mail->SMTPAuth   = true; 
		$mail->Username   = $user_name; 
		$mail->Password   = $user_password; 
		$mail->SMTPSecure = 'tls';
		$mail->From       = $hr_mail;
		$mail->FromName   = $sender_name;
		$mail->AddAddress($cc_mail);
		$mail->IsHTML(true);
		$mail->Subject    = "Document Upload link";
		$mail->Body       = $msg;
		$mail->Send();
	}

	public function get_array_data($module_name){
		//DB NAME
		$db_qry             = "SELECT DATABASE() AS db";
		$row                = $this->is_exit_data($db_qry);
		$db_name            = $row[0]->db;
		//COMPANY INFO
		$company_qry        = 'SELECT * FROM cw_company_information WHERE cw_company_information.trans_status = 1';
		$company_rslt       = $this->is_exit_data($company_qry);
		//PRINT TABLE
		$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';
		$table_result       =  $this->is_exit_array($table_qry);
		foreach($table_result as $arr){
			$print_table_result[$arr['print_table_for_id']][] = $arr;
		}
		//PRINT TABLE WHERE
		$where_qry          = 'SELECT where_condition,where_for_id FROM cw_print_table_where WHERE trans_status = 1';
		$where_result       = $this->is_exit_array($where_qry);
		foreach($where_result as $arr){
			$where_result[$arr['where_for_id']] = $arr;
		}
		//FORM SETTING
		$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_result_arr    = $this->is_exit_array($form_qry);
		foreach($form_result_arr as $arr){
			$form_result_array[$arr['prime_module_id']][$arr['label_name']][] = $arr;
		}
		$form_set_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_set_rslt      = $this->is_exit_array($form_set_qry);
		$form_set_rslt      = array_reduce($form_set_rslt, function($result, $arr){			
	    	$result[$arr['label_name']] = $arr;
	    	return $result;
		}, array());
		//PRINT DESIGN
		$design_qry         = 'SELECT print_design_for,print_design from cw_print_design where trans_status = 1';
		$design_result      = $this->is_exit_array($design_qry);
		$design_arr = array();
		foreach($design_result as $d_arr){
			$design_arr[$d_arr['print_design_for']] = $d_arr['print_design'];
		}
		$payslip_based_on   = $company_rslt[0]->payslip_based_on;
		//Get Payslip based on column name - START
		$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_result        = $this->is_exit_array($name_qry);
		$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];
		}
		$final_result       = array('db_name' => $db_name,'print_table_result' => $print_table_result,'where_result'=>$where_result,'form_result_array'=>$form_result_array,'form_set_rslt'=>$form_set_rslt,'design_arr'=>$design_arr,'payslip_based_on'=>$payslip_based_on,'payslip_arr'=>$payslip_arr);
		return $final_result;
	}
	// ONBOARD PROCESS [MS 05-09-2024]
	// FUNCTION FOR GET TOKEN 
	public function get_token(){
		$curl = curl_init();
		curl_setopt_array($curl, array(
		  CURLOPT_URL => $this->$app_url.'/login/',
		  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 =>'{
			"email": "api@uds.in",
			"password": "9mWLbouyFEQUqyN"
		}',
		  CURLOPT_HTTPHEADER => array(
			'Content-Type: application/json'
		  ),
		));
		$response = curl_exec($curl);
		curl_close($curl);
		$token_data       = json_decode($response);
		$api_token        = $token_data->session->token;
		return $api_token;
	}
	//
	public function onboard_success_upd($aadhar_card_no,$employee_code,$api_token){
		$curl           = curl_init();
		curl_setopt_array($curl, array(
		CURLOPT_URL => $this->$app_url.'/code/',
		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 =>'{
			"aadhar_number": "'.$aadhar_card_no.'",
			"employee_code":"'.$employee_code.'"
		}',
		CURLOPT_HTTPHEADER => array(
			'Authorization: Bearer '.$api_token,
			'Content-Type: application/json'
		),
		));
		$response               = curl_exec($curl);
		curl_close($curl);
  		$response               = json_decode($response);
		$data                   = $response->data;
		$emp_upd_qry            = '';
		$values                 = '';
		$emp_log_values         = '';
		$log_qry_cols           = '';
		$get_api_col_qry        = 'SELECT our_key,api_key FROM cw_api_mapping where flag_for = "EMP CODE UPDATE API"';
		$get_api_col_info       = $this->runQuery($get_api_col_qry);
		$get_api_col_rslt       = $this->result($get_api_col_info);
		mysqli_next_result($this->db);
		$check_col_arr          = array();
		// GET API KEY AND OUR KEY IN DUNAMIC WAY [MS]
		foreach($get_api_col_rslt as $key => $val){
			$check_col_arr[$get_api_col_rslt[$key]->api_key] = $get_api_col_rslt[$key]->our_key;
		}
		
		foreach($data->$aadhar_card_no as $key => $val){
			if(in_array($key,array_keys($check_col_arr))){
				if($check_col_arr[$key] === 'nom_dob' || $check_col_arr[$key] === 'nom_two_dob'){
					$val   = date('Y-m-d',strtotime("$val"));
				}
				$values        .= "`$check_col_arr[$key]` = '$val' ,";
				$log_qry_cols  .= "$check_col_arr[$key] as $key,";
			}
		}
		if($values){
			$created_on         = date("Y-m-d H:i:s");
			//GET OLD DATA FOR  EMPLOYEE LOG INSERT
			$log_qry_cols       = rtrim($log_qry_cols,',');
			$emp_log_qry        = 'SELECT prime_employees_id,employee_code,emp_name as employee_name,'.$log_qry_cols.' FROM cw_employees WHERE aadhar_card_no = "'.$aadhar_card_no.'" ';
			$emp_log_info       = $this->runQuery($emp_log_qry);
			$emp_log_rslt       = $this->result($emp_log_info);
			mysqli_next_result($this->db);

			foreach($emp_log_rslt[0] as $key => $val){
				if($check_col_arr[$key]){
					if($data->$aadhar_card_no->$key !== $val){
						$emp_log_values .= '("'.$emp_log_rslt[0]->prime_employees_id.'","'.$emp_log_rslt[0]->employee_code.'","'.$emp_log_rslt[0]->employee_name.'","'.$check_col_arr[$key].'","'.$val.'","'.$data->$aadhar_card_no->$key.'","onboard api","","'.$created_on.'",1),';
					}
				}
			}
			$emp_log_values     = rtrim($emp_log_values,',');

			// UPDATE IN EMPLOYEE MASTER
			$emp_upd_qry        = 'UPDATE cw_employees SET '.rtrim($values,',') .'WHERE aadhar_card_no = "'.$aadhar_card_no.'"';
			$emp_upd_info       = $this->runQuery($emp_upd_qry);
			if($emp_upd_info){
				
				// INSERT IN EMPLOYEES LOG
				$log_ins_qry    = 'INSERT INTO cw_employees_log(prime_employees_id,employee_code,emp_name,label_name,old_value,new_value,module_name,trans_created_by,trans_created_date,trans_status) VALUES '.$emp_log_values;
				if($emp_log_values){
					$log_ins    = $this->runQuery($log_ins_qry);
				}

				// UPDATAION IN ONBOARD SUCCESS LIST TABLE
				$upd_qry       = 'UPDATE cw_onboard_success_list SET onboard_status = 1,trans_updated_date = "'.$created_on.'"  WHERE aadhar_card_no = "'.$aadhar_card_no.'"'; 
				$upd_qry_info  = $this->runQuery($upd_qry);
			}		
		}
		return $upd_qry_info; 
	}
	# PASSWORD UPDATE BASED ON ENCRYPTION
	public function update_password(){
		$select_qry             = 'SELECT employee_code,password FROM cw_employees WHERE termination_status = 0 and trans_status = 1';
		$select_info            = $this->runQuery("$select_qry");
		$select_rslt            = $this->result_array($select_info);		
		foreach($select_rslt as $val){
			$employee_code      = $val['employee_code'];
			$password           = $val['password'];
			$enc_password       = $this->cryptoEncrypt($password);
			$upd_qry            = 'UPDATE cw_employees SET  `password` = "'.$enc_password.'" WHERE employee_code = "'.$employee_code.'"';
			$upd_info           = $this->runQuery("$upd_qry");
		}
		if($upd_info){
			return true;
		}else{
			return false;
		}
	}
	//Five STAGES OF ENCRYPTION AND DECRYPTION 
	public function cryptoEncrypt($data){
		try {
			// For Password Encryption
			$hash1     = hash('sha512', $data);
			$hash2     = hash('sha1', $hash1);
			$Hash3     = hash('haval160,4', $hash2); 
			$Hash4     = hash('haval160,5', $Hash3); 
			// Generate the HMAC hash
			$finalhash = hash_hmac('sha256', $Hash4, $this->enckey);		
			return $finalhash;	
		} catch (Exception $e) {
			// Log the error or handle it as needed
			error_log("Encryption Error: " . $e->getMessage()); // Log the error for debugging
			return false;
		}
	}
	// ONBOARD INACTIVE 
	public function emp_inactive_upd($aadhar_card_no,$employee_code,$dol,$api_token){
		$curl = curl_init();
		curl_setopt_array($curl, array(
		CURLOPT_URL => $this->$app_url.'/status/',
		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 =>'{
			"aadhar_number": "'.$aadhar_card_no.'",
			"employee_code":"'.$employee_code.'",
			"date":"'.$dol.'",
			"status":false
		}',
		CURLOPT_HTTPHEADER => array(
			'Authorization: Bearer '.$api_token,
			'Content-Type: application/json'
		),
		));
		$response = curl_exec($curl);
		curl_close($curl);
		return $response;
	}
}
?>