<?php
include '../connect/cms-config.php' ;
include '../requires/function.php' ;


// Check the order within 5 minutes
$from_date       = date( 'Y-m-d H:i:s', strtotime( "-6 minutes" ) ) ;
$to_date         = date( 'Y-m-d H:i:s', strtotime( "-1 minutes" ) ) ;

// Check the order within in 24 hours
$hours1          = date( 'Y-m-d H:i', strtotime( "-24 hours" ) ) ;

$select_order    = $mysqli->query( "SELECT order_id, staff_id, sonumber, created_at FROM staff_rms_prepaid_order
				   		   		    WHERE deleted_at IS NULL AND status IN ( 'pending', 'progress' ) AND ( ( created_at BETWEEN '".$from_date."' AND '".$to_date."' ) OR created_at LIKE '%".$hours1."%' )" ) ;
if ( $select_order->num_rows > 0 ){
	while ( $row_order = $select_order->fetch_assoc() ){

		$rms_content   = [
            'topUpReferenceId' => $row_order['sonumber']
        ] ;
		$rms_call      = rmsCall( 'pinless/checktransactionstatus', $rms_content ) ;
        saveLog( 'rms-api', 'Check Prepaid Status', $rms_content, $rms_call ) ;

		if ( $rms_call['respCode'] == '00' ){
			if ( $mysqli->query( "UPDATE staff_rms_prepaid_order SET
								  rms_order_id   = '".$rms_call['orderId']."',
								  status 	     = 'confirmed'
								  WHERE order_id = '".$row_order['order_id']."'" ) ){
				$status = '200' ;
			}
		}else{
			if ( $mysqli->query( "UPDATE staff_rms_prepaid_order SET
								  status 	     = 'progress'
								  WHERE order_id = '".$row_order['order_id']."'" ) ){
				$status = '202' ;
			}
		}
	}
}


// after transaction over 24 hours, auto cancel order and refund the wallet
$hours1          = date( 'Y-m-d H:i', strtotime( "-25 hours" ) ) ;
$select_order    = $mysqli->query( "SELECT order_id, staff_id, sonumber, dialcode, mobile, amount FROM staff_rms_prepaid_order
				   		   		    WHERE deleted_at IS NULL AND status IN ( 'pending', 'progress' ) AND ( created_at LIKE '%".$hours1."%' )" ) ;
if ( $select_order->num_rows > 0 ){
	while ( $row_order = $select_order->fetch_assoc() ){

		saveLog( 'rms-api', 'Auto Cancel Prepaid', [], $row_order ) ;

		if ( $mysqli->query( "UPDATE staff_rms_prepaid_order SET
							  status 	     = 'cancelled'
							  WHERE order_id = '".$row_order['order_id']."'" ) ){
			
			// refund the wallet
            $remark    = 'You have been refunded the wallet from prepaid order '.$row_order['dialcode'].'-'.$row_order['mobile'].' (' . $row_order['sonumber'] . ')' ;
            walletMovement( 'staff_rms_prepaid_order', $row_order['order_id'], 'plus', 'normal', $row_order['staff_id'], $row_order['amount'], $remark ) ;

		}
		
	}
}

?>