<?php

//Requiring the flow api client
require_once "../flowsp/lib/FlowApi.class.php";
require_once "../flowsp/lib/Config.class.php";
require_once "../flowsp/lib/flowhelper.php";
use FlowApi\ServiPag\FlowApi;
use FlowApi\ServiPag\Config;

// Required File Includes from WHMCS
include("../../../includes/functions.php");
include("../../../includes/gatewayfunctions.php");
include("../../../includes/invoicefunctions.php");

if (file_exists('../../../dbconnect.php')) {
	include '../../../dbconnect.php';
} else if (file_exists('../../../init.php')) {
	include '../../../init.php';
}

logActivity('Entering callback/flowsp.php', 0);
logTransaction(Config::GATEWAY_NAME, $_POST, "Flow response of calling the callback url passed previously");

try{
	//Configuring the necessary params to call the FLOW API
	$flowToken = filter_input(INPUT_POST, 'token', FILTER_SANITIZE_STRING);
	$flowConfig = getGatewayVariables(Config::GATEWAY_NAME);
	$method = "GET";
	$endpoint = Config::ENDPOINTS[$flowConfig['mode']];
	$flowParams = array(
		'token'		=>	$flowToken
	);
	$service = Config::SERVICES['paymentStatus'];
	
	$flowApi = new FlowApi();
	$flowApi->setKeys($flowConfig['apiKey'], $flowConfig['secretKey']);
	
	$flowOrderData = $flowApi->send($service, $flowParams, $endpoint, $method);
	logTransaction(Config::GATEWAY_NAME, $flowOrderData, "Result of calling API/payment/getStatus");
	logModuleCall(Config::GATEWAY_NAME, "Calling API: {$service}", $flowParams, $flowOrderData, null, null);

	//Checks if the invoice ID or commerce Order coming from flow is a valid one,
	
	$commerceOrder = $flowOrderData['commerceOrder'];
	$invoiceId = checkCbInvoiceID($commerceOrder, Config::GATEWAY_NAME);
	$flowOrderId = $flowOrderData["flowOrder"];
	$amountPaidInFlow = $flowOrderData['paymentData']['amount'];
	$fees = $flowOrderData['paymentData']['fee'];
	$statusInFlow = $flowOrderData['status'];
	//Checks if there wasn't already a payment transaction with the given ID (this is used to prevent duplicates)
	checkCbTransID($flowOrderId);
	
	/*if(FlowHelper::isTesting($flowOrderData, $flowConfig)){
		logActivity('Setting up the simulation...', 0);
		FlowHelper::setUpProductionEnvSimulation($flowOrderData);
	}*/

	$statusInFlow = $flowOrderData['status'];

	if(FlowHelper::isPendingInFlow($statusInFlow)){
		logActivity('Order is pending. Doing nothing...', 0);
	}
	elseif(FlowHelper::isPaidInFlow($statusInFlow)){

		logActivity('Order is paid in Flow. Adding payment.', 0);
		addInvoicePayment(
			$invoiceId,
			$flowOrderId,
			$amountPaidInFlow,
			$fees,
			Config::GATEWAY_NAME
		);
	}
	elseif(FlowHelper::isCanceledInFlow($statusInFlow)){
		logActivity('Order was canceled. Doing nothig...', 0);
	}
	else{
		logActivity('Order rejected. Doing nothing again...', 0);
	}
	
	return;
	
	
}catch (Exception $e){
	error_log($e->getMessage());
	logActivity('There has been an unexpected error. Code: '.$e->getCode().' Message: '.$e->getMessage());
}
