<?php
// get these values from your DB.
require_once('config.php');
require_once('send_notification_v1.php');
require_once('f_insert_notification_log.php');
require_once('find_online_tablet.php');
require_once('f_send_email_notification.php');
$error_message;
$valid = true;


/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
     die( print_r( sqlsrv_errors(), true ));
}


$json = file_get_contents('php://input');

// Converts it into a PHP object
$data = json_decode($json, true);

$site_cd = $data['site_cd'];
$EmpID = $data['EmpID'];
$LOGINID = $data['LOGINID'];

$pur_mst_porqnnum = $data['pur_mst_porqnnum'];
$pur_mst_rowID = $data['pur_mst_rowID'];
$remark = $data['remark'];
$header_audit_date = $data['header_audit_date'];
$dft_mst_pur_email_approver = $data['dft_mst_pur_email_approver'];
$dft_mst_pur_email_requestor = $data['dft_mst_pur_email_requestor'];
$dft_mst_generate_po = $data['dft_mst_generate_po'];
$pur_mst_status = $data['pur_mst_status'];
$dvc_id = $data['dvc_id'];


	$sql_pur_mst ="Select audit_date,pur_mst_create_by,pur_mst_create_date,
				pur_mst_crd_costcenter,pur_mst_chg_account,pur_mst_porqnnum,RowID,pur_mst_tot_cost 
			   from pur_mst (NOLOCK)  
			   Where site_cd = ? 
			   and  RowID = ?";
			
	$params_pur_mst = array($site_cd,$pur_mst_rowID);

	$stmt_pur_mst = sqlsrv_query( $conn, $sql_pur_mst,$params_pur_mst);

	if( !$stmt_pur_mst ) {
		
		 $error_message = "Error selecting mtr_mst";
		 returnError($error_message);
		 die( print_r( sqlsrv_errors(), true));
		 
	}	

	do {
		
		while ($row = sqlsrv_fetch_array($stmt_pur_mst, SQLSRV_FETCH_ASSOC)) {		
		
			$audit_date = $row['audit_date']->format('Y-m-d H:i:s');
			
			$pur_mst_create_by =  $row['pur_mst_create_by'];		
			$pur_mst_create_date = $row['pur_mst_create_date']->format('Y-m-d H:i:s');			
			$pur_mst_crd_costcenter =  $row['pur_mst_crd_costcenter'];			
			$pur_mst_chg_account =  $row['pur_mst_chg_account'];			
			$pur_mst_porqnnum =  $row['pur_mst_porqnnum'];			
			$RowID =  $row['RowID'];			
			$pur_mst_tot_cost =  $row['pur_mst_tot_cost'];			
			//echo $audit_date;
		}
		
	} while ( sqlsrv_next_result($stmt_pur_mst) );
	  sqlsrv_free_stmt( $stmt_pur_mst);
	  
	  
if($header_audit_date <> $audit_date){
//echo $header_audit_date;
//echo $audit_date;
		 
sqlsrv_rollback( $conn );
$error_message = "The PR audit date had been changed. The record already updated by another user. Please cancel and retrieve the record again.";
returnError($error_message);
				
}else{

	  
$sql_pur_det = "UPDATE pur_det SET 
				pur_det_note1 = ?,				
				audit_user=?,
				audit_date=getdate(),
				mbl_audit_user=?,		
				mbl_audit_date=getdate() 
				WHERE site_cd=? 
				and mst_rowid = ?";


$params_pur_det = array($remark ,$LOGINID,$LOGINID,$site_cd,$pur_mst_rowID);
$stmt_update_pur_det = sqlsrv_query( $conn, $sql_pur_det,$params_pur_det);	
		
if( !$stmt_update_pur_det ) {
	$error_message = "Error update table (mtr_det)";
	returnError($error_message);
	die( print_r( sqlsrv_errors(), true));
}sqlsrv_free_stmt($stmt_update_pur_det);



$sql_pur_app ="SELECT	ll_empl_cnt = Count(pur_app_empl_id), ls_approver = Min(pur_app_empl_id)
				FROM	pur_app (NOLOCK)
				WHERE	site_cd = ?
				AND		mst_rowid = ?
				AND		pur_app_level= ?";

	$params_pur_app = array($site_cd,$pur_mst_rowID,1);

	$stmt_select_pur_app = sqlsrv_query( $conn, $sql_pur_app,$params_pur_app);	

	if( !$stmt_select_pur_app ) {

	 $error_message = "Error selecting mtr_mst";
	 returnError($error_message);
	 die( print_r( sqlsrv_errors(), true));
	 
	}	

	do {

	while ($row = sqlsrv_fetch_array($stmt_select_pur_app, SQLSRV_FETCH_ASSOC)) {		

		$ll_empl_cnt = $row['ll_empl_cnt'];		
		$ls_approver = $row['ls_approver'];

				//echo $ll_empl_cnt ;		
				//echo $ls_approver ;											

	}

	} while ( sqlsrv_next_result($stmt_select_pur_app) );
	sqlsrv_free_stmt( $stmt_select_pur_app);  
					
	if($ll_empl_cnt == 1){
		
		$sql_pur_mst = "UPDATE pur_mst  SET 
						pur_mst_purq_approve = 'W',	
						pur_mst_status = '".$pur_mst_status."',	
						pur_mst_cur_app_level = 0 ,	
						pur_mst_approver ='".$ls_approver."',
						pur_mst_release_for_app = '0',						
						audit_user='".$LOGINID."',
						audit_date=getdate(),
						mbl_audit_user='".$LOGINID."',		
						mbl_audit_date=getdate() 
						WHERE site_cd='".$site_cd."' 
						and RowID ='".$pur_mst_rowID."'";


			
			$stmt_update_pur_mst = sqlsrv_query( $conn, $sql_pur_mst);	
					
			if( !$stmt_update_pur_mst ) {
				$error_message = "Error update table (pur_mst)";
				returnError($error_message);
				die( print_r( sqlsrv_errors(), true));
			}sqlsrv_free_stmt( $stmt_update_pur_mst);
		
	}else if($ll_empl_cnt > 1){
		
		$sql_pur_mst = "UPDATE pur_mst  SET 
						pur_mst_purq_approve = 'W',	
						pur_mst_status = '".$pur_mst_status."',	
						pur_mst_cur_app_level = 0 ,	
						pur_mst_approver ='".$ls_approver."'+ '...',
						pur_mst_release_for_app = '0',						
						audit_user='".$LOGINID."',
						audit_date=getdate(),
						mbl_audit_user='".$LOGINID."',		
						mbl_audit_date=getdate()  
						WHERE site_cd='".$site_cd."' 
						and RowID ='".$pur_mst_rowID."'";


			
			$stmt_update_pur_mst = sqlsrv_query( $conn, $sql_pur_mst);	
					
			if( !$stmt_update_pur_mst ) {
				$error_message = "Error update table (pur_mst)";
				returnError($error_message);
				die( print_r( sqlsrv_errors(), true));
			}sqlsrv_free_stmt( $stmt_update_pur_mst);
		
	}else if($ll_empl_cnt == 0){
		
		
		$sql_pur_mst = "UPDATE pur_mst  SET 
						pur_mst_purq_approve = 'W',	
						pur_mst_status = '".$pur_mst_status."',	
						pur_mst_cur_app_level = 0 ,	
						pur_mst_approver =Null,
						pur_mst_release_for_app = '0',						
						audit_user='".$LOGINID."',
						audit_date=getdate(),
						mbl_audit_user='".$LOGINID."',		
						mbl_audit_date=getdate()  
						WHERE site_cd='".$site_cd."' 
						and RowID ='".$pur_mst_rowID."'";


			
			$stmt_update_pur_mst = sqlsrv_query( $conn, $sql_pur_mst);	
					
			if( !$stmt_update_pur_mst ) {
				$error_message = "Error update table (pur_mst)";
				returnError($error_message);
				die( print_r( sqlsrv_errors(), true));
			}sqlsrv_free_stmt( $stmt_update_pur_mst);
		
		
	}			


		$sql_pur_app = "UPDATE pur_app  SET 
						pur_app_status = 'P',	
						pur_app_desc = Null ,	
						pur_app_date =Null,												
						audit_user='".$LOGINID."',
						audit_date=getdate(),
						mbl_audit_user='".$LOGINID."',		
						mbl_audit_date=getdate()  
						WHERE site_cd='".$site_cd."' 
						and mst_RowID ='".$pur_mst_rowID."'";

		$stmt_update_pur_app = sqlsrv_query( $conn, $sql_pur_app);	
				
		if( !$stmt_update_pur_app ) {
			$error_message = "Error update table (pur_app)";
			returnError($error_message);
			die( print_r( sqlsrv_errors(), true));
		}sqlsrv_free_stmt( $stmt_update_pur_app);
		
		
		
		$sql_pur_ls2 = "UPDATE pur_ls2  SET 
						pur_ls2_datetime2 = GETDATE(),	
						pur_ls2_numeric1 = '0',												
						audit_user='".$LOGINID."',
						audit_date=GETDATE()
						WHERE pur_ls2_datetime2 is NULL 
						and site_cd='".$site_cd."'
						and mst_RowID ='".$pur_mst_rowID."'";

		$stmt_update_pur_ls2 = sqlsrv_query( $conn, $sql_pur_ls2);	
				
		if( !$stmt_update_pur_ls2 ) {
			$error_message = "Error update table (pur_ls2)";
			returnError($error_message);
			die( print_r( sqlsrv_errors(), true));
		}sqlsrv_free_stmt( $stmt_update_pur_ls2);
		
		
		$sql_insert_pur_ls2 = "INSERT pur_ls2 
					(		site_cd,				mst_RowID ,				pur_ls2_varchar1,		pur_ls2_varchar2,		
							pur_ls2_varchar3,		pur_ls2_datetime1, 		pur_ls2_datetime2,		pur_ls2_numeric1,		
							audit_user,				audit_date,				mbl_audit_user,			mbl_audit_date ) 
			VALUES  (		?,						?,						?,						?,					
							?,						GETDATE (), 			NULL,					NULL,					
							?,						GETDATE (),				?,						GETDATE ())";
								
								
	$params_pur_ls2 = array($site_cd,$pur_mst_rowID,$pur_mst_porqnnum,$pur_mst_status,$EmpID,$LOGINID,$LOGINID);				
	$stmt_pur_ls2 = sqlsrv_query( $conn, $sql_insert_pur_ls2,$params_pur_ls2);

	if( !$stmt_pur_ls2 ) {
		$error_message = "Error insert table (INSERT Table pur_ls2)";
		returnError($error_message);
		die( print_r( sqlsrv_errors(), true));
	}	
	sqlsrv_free_stmt( $stmt_pur_ls2);
	
	
	  
		//Send EMail
		$sql_emp_mst = "
		SELECT emp_det.emp_det_email_id,e.emp_mst_name,e.emp_mst_empl_id
		FROM emp_mst e (NOLOCK)
		LEFT JOIN emp_det (NOLOCK) ON e.site_cd = emp_det.site_cd AND e.RowID = emp_det.mst_RowID
		WHERE e.site_cd = '".$site_cd."'
		AND e.emp_mst_empl_id IN (
			SELECT pur_app_empl_id 
			FROM pur_app (NOLOCK)
			WHERE mst_RowID = '".$pur_mst_rowID."' AND site_cd = '".$site_cd."' AND pur_app_empl_id <> '".$EmpID."'
			
			UNION ALL

			SELECT pur_mst_create_by 
			FROM pur_mst (NOLOCK)
			WHERE RowID = '".$pur_mst_rowID."' AND site_cd = '".$site_cd."'
		)";

		$stmt_emp_mst = sqlsrv_query($conn, $sql_emp_mst);

		if (!$stmt_emp_mst) {
			$error_message = "Error selecting emp_mst";
			returnError($error_message);
			die(print_r(sqlsrv_errors(), true));
		}

		$json = array();
		date_default_timezone_set("Asia/Kuala_Lumpur");
		$date = date("Y-m-d H:i");
		while ($row = sqlsrv_fetch_array($stmt_emp_mst, SQLSRV_FETCH_ASSOC)) {
			if (!empty($row['emp_det_email_id'])) { // ✅ skip null or empty
				//$json[] = $row['emp_det_email_id'];
				$emp_det_email_id = $row['emp_det_email_id'];
				$emp_mst_name = $row['emp_mst_name'];
				$emp_mst_empl_id = $row['emp_mst_empl_id'];
				
				$body = '
						<!DOCTYPE html>
						<html>
						  <body style="margin:0; padding:0; background-color:#f4f7fa; font-family: Arial, sans-serif; color:#333;">
							<table width="100%" cellpadding="0" cellspacing="0" style="background-color:#f4f7fa;">
							  <tr>
								<td align="center">
								  <table width="600" cellpadding="0" cellspacing="0" style="background-color:#ffffff; border-collapse:collapse; border:1px solid #e3e3e3; margin:20px auto;">
									
									<!-- Header -->
									<tr>
									  <td style="background-color:#d9534f; color:#ffffff; text-align:center; padding:20px;">
										<h1 style="font-size:24px; margin:0;">Purchase Request Rejected</h1>
										<p style="margin:5px 0 0;">We regret to inform you that your request has been Rejected.</p>
									  </td>
									</tr>

									<!-- Rejection Details -->
									<tr>
									  <td style="padding:20px;">
										<h2 style="font-size:18px; color:#d9534f; margin:0 0 10px;">Rejection Details</h2>
										<p style="font-size:16px; margin:0 0 10px;"><strong>Rejected By:</strong> '.($EmpID . ' : ' . $emp_mst_name).'</p>
										<p style="font-size:16px; margin:0 0 10px;"><strong>Rejected Date:</strong> '.$date.'</p>
										<p style="font-size:16px; margin:0;"><strong>Reject Reason:</strong> '.$remark.'</p>
									  </td>
									</tr>

									<!-- Purchase Request Details -->
									<tr>
									  <td style="padding:20px;">
										<h2 style="font-size:18px; color:#d9534f; margin:0 0 10px;">Purchase Request Details</h2>
										<table width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse; font-size:16px;">
										  <tr>
											<th align="left" style="padding:8px 12px; border:1px solid #e3e3e3; background-color:#fbe5e5; color:#d9534f;">PR Number</th>
											<td style="padding:8px 12px; border:1px solid #e3e3e3;">'.$pur_mst_porqnnum.'</td>
										  </tr>
										  <tr>
											<th align="left" style="padding:8px 12px; border:1px solid #e3e3e3; background-color:#fbe5e5; color:#d9534f;">Request By</th>
											<td style="padding:8px 12px; border:1px solid #e3e3e3;">'.$pur_mst_create_by.' : '.$emp_mst_name.'</td>
										  </tr>
										  <tr>
											<th align="left" style="padding:8px 12px; border:1px solid #e3e3e3; background-color:#fbe5e5; color:#d9534f;">Request Date</th>
											<td style="padding:8px 12px; border:1px solid #e3e3e3;">'.$pur_mst_create_date.'</td>
										  </tr>
										  <tr>
											<th align="left" style="padding:8px 12px; border:1px solid #e3e3e3; background-color:#fbe5e5; color:#d9534f;">Charge Cost Center</th>
											<td style="padding:8px 12px; border:1px solid #e3e3e3;">'.$pur_mst_crd_costcenter.'</td>
										  </tr>
										  <tr>
											<th align="left" style="padding:8px 12px; border:1px solid #e3e3e3; background-color:#fbe5e5; color:#d9534f;">Charge Cost Account</th>
											<td style="padding:8px 12px; border:1px solid #e3e3e3;">'.$pur_mst_chg_account.'</td>
										  </tr>
										  <tr>
											<th align="left" style="padding:8px 12px; border:1px solid #e3e3e3; background-color:#fbe5e5; color:#d9534f;">Total PR Cost</th>
											<td style="padding:8px 12px; border:1px solid #e3e3e3;">'.$pur_mst_tot_cost.'</td>
										  </tr>
										</table>
									  </td>
									</tr>

									<!-- Footer -->
									<tr>
									  <td style="background-color:#d9534f; color:#ffffff; text-align:center; padding:20px;">
										<p style="margin:0 0 5px;">If you need further assistance, please reach out to us at 
										  <a href="mailto:support@example.com" style="color:#ffffff; text-decoration:underline;">support@evantage.com.my</a>.
										</p>
										<p style="margin:0;">&copy; '.date("Y").' Your Company Name</p>
									  </td>
									</tr>
								  </table>
								</td>
							  </tr>
							</table>
						  </body>
						</html>';

					 $title  = 'CMMS Purchase Request Rejected: ' . $pur_mst_porqnnum;
					 $eml_log_from='CMMS ADMIN';
					 $eml_log_to_email = array();
					 $eml_log_to_email[] = $emp_det_email_id;
					 $audit_user    =  $LOGINID;
					 $module   =     'Purchase Request';
					 $action   =     'Purchase Request Rejected';
					 $trigger_from   =     NULL;
			 
					 send_email($site_cd,$eml_log_from,$eml_log_to_email,$title,$body,$audit_user,$pur_mst_porqnnum,$module,$action,$trigger_from,NULL,NULL,NULL);
		
		
			}
		}
		sqlsrv_free_stmt($stmt_emp_mst);
		
		
		
		if(!empty($emp_det_email_id)){
	
	
	
			$sql_insert_wko_ls7 = "	INSERT wko_ls7 
							(	site_cd,				mst_RowID,					wko_ls7_level,			wko_ls7_emp_id, 
								wko_ls7_due_days,		wko_ls7_wo_org_date,		wko_ls7_due_date,		wko_ls7_total_days, 
								audit_user ,			audit_date,					mbl_audit_user,			mbl_audit_date ) 
					VALUES 
							(	?,						?,							?,						?,
								?,						GetDate(),					NULL,					NULL,
								?,						GetDate(),					?,			GetDate())";


			$params_wko_ls7 = array($site_cd,$pur_mst_rowID,'1',$emp_det_email_id,'1',$LOGINID,$LOGINID);	
			$stmt = sqlsrv_query( $conn, $sql_insert_wko_ls7,$params_wko_ls7);	
			if( !$stmt ) {
			$error_message = "Error insert table (INSERT Table wko_ls7)";
			returnError($error_message);
			die( print_r( sqlsrv_errors(), true));
			}	
			sqlsrv_free_stmt( $stmt);


	
	
			$title = "Purchase Request Rejected";
			$body = 'CMMS Purchase Request Rejected: ' . $pur_mst_porqnnum;
			$module = "Purchase Request";
			$message_assign = "Rejected By:" .($EmpID . ' : ' . $emp_mst_name). "\r\n" . "Rejected Date:" .$date. "\r\n" ."Reject Reason:" .$remark;

			
			$insert_ntf4 = insert_notification_log($site_cd, $EmpID, $pur_mst_create_by, $pur_mst_porqnnum, $title, $body, $message_assign, $module, $dvc_id, $LOGINID);
		
			foreach($insert_ntf4 as $x => $val) {
				
				$row = $x = $val["row"];
				$insert_ntf = $x = $val["insert_ntf"];
				
				//echo '<pre>'; print_r($row); echo '</pre>';
				//echo '<pre>'; print_r($insert_ntf); echo '</pre>';		
				
			
			}
		
	
			//Get New Value Assignto Online Token
			$tkn_token_2 = get_online($pur_mst_create_by, $site_cd);
			
			//Notify token user
				if (sizeof($tkn_token_2) > 0){
					
							
					foreach($tkn_token_2 as $x => $val) {
						
						$tokenlist = $x = $val["token"];
						$RowID = $x = $val["RowID"];
						$tkn_site = $x = $val["tkn_site"];
						
						//echo '<pre>'; print_r($tkn_site); echo '</pre>';
						//echo '<pre>'; print_r($RowID); echo '</pre>';			
						
						
						push_notification_android($tokenlist,  "Purchase Request Rejected: (" . $pur_mst_porqnnum . ")",'Purchase Request Rejected', $site_cd, $tokenlist, $RowID, $row, $tkn_site, $LOGINID);						
						
					
					}		
				}
		}
		
		
		
	
	


if($stmt_update_pur_det){
	
	if($stmt_select_pur_app){
		
		if($ll_empl_cnt == 1){
			if($stmt_update_pur_mst){
					sqlsrv_commit( $conn );
					sqlsrv_close( $conn);	
					returnData();
			}else{
					sqlsrv_rollback( $conn );
					$error_message = "Transaction rolled back.<br />";
					returnError($error_message); 
			}
			
		}else if($ll_empl_cnt > 1){
			if($stmt_update_pur_mst){
					sqlsrv_commit( $conn );
					sqlsrv_close( $conn);	
					returnData();
			}else{
					sqlsrv_rollback( $conn );
					$error_message = "Transaction rolled back.<br />";
					returnError($error_message); 
			}
			
		}else if($ll_empl_cnt == 0){
			if($stmt_update_pur_mst){
					sqlsrv_commit( $conn );
					sqlsrv_close( $conn);	
					returnData();
			}else{
					sqlsrv_rollback( $conn );
					$error_message = "Transaction rolled back.<br />";
					returnError($error_message); 
			}
			
		}
		
		
	}else{
		sqlsrv_rollback( $conn );
		$error_message = "Transaction rolled back.<br />";
		returnError($error_message); 
	}	

	
	
}else{
	sqlsrv_rollback( $conn );
	$error_message = "Transaction rolled back.<br />";
	returnError($error_message); 
}	

}


function returnData(){
	$returnData = array(
		'status' => 'SUCCESS',
		'message' => 'The purchase request had successfully rejected.');
	echo json_encode($returnData);
}

function returnError($error_message){
	$json = array();
	
	$returnData = array(
	'status' => 'ERROR',
	'message' => $error_message);
	
	echo json_encode($returnData);
		
}


 
?>
