<?php

namespace FlowApi\Webpay;
require_once __DIR__."/FlowApi.class.php";
require_once __DIR__."/Config.class.php";

use FlowApi\Webpay\FlowApi;
use FlowApi\Webpay\Config;
use WHMCS\Database\Capsule;

// 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';
}

try{
    
    define("WRONG_CURRENCY_ERROR_CODE", 1001);
    
    global $CONFIG;
    $flowConfig = getGatewayVariables(Config::GATEWAY_NAME);

    $flowApi = new FlowApi;
    $flowApi->setKeys($flowConfig['apiKey'], $flowConfig['secretKey']);

    logActivity('Entering the intermediate.php file of '.Config::GATEWAY_NAME.' to create the FLOW order');
    $mode = $flowConfig['mode'];
    $paymentMode = Config::PAYMENT_MODE;
    $service = Config::SERVICES["payment"];
    $endpoint = Config::ENDPOINTS[$mode];

    $args = array(
        'commerceOrder'     =>  FILTER_SANITIZE_STRING,
        'amount'            =>  FILTER_SANITIZE_STRING,
        'email'             =>  FILTER_SANITIZE_STRING,
        'subject'           =>  FILTER_SANITIZE_STRING,
        'urlConfirmation'   =>  FILTER_SANITIZE_STRING,
        'urlReturn'         =>  FILTER_SANITIZE_STRING,
        'currency'          =>  FILTER_SANITIZE_STRING,
    );

    $postParams = filter_input_array(INPUT_POST, $args);

    if($postParams['currency'] !== 'CLP'){
        throw new \Exception("Payment can only be made with chilean pesos (CLP). {$postParams['currency']} used instead.", constant("WRONG_CURRENCY_ERROR_CODE"));
    }
    
    $flowParams = array(
        'paymentMethod'     =>  $paymentMode,
        'commerceOrder'     =>  $postParams['commerceOrder'],
        'amount'            =>  $postParams['amount'],
        'email'             =>  $postParams['email'],
        'subject'           =>  $postParams['subject'],
        'urlConfirmation'   =>  $postParams['urlConfirmation'],
        'urlReturn'         =>  $postParams['urlReturn'],
        'currency'          =>  $postParams['currency']
    );

    $response = $flowApi->send($service, $flowParams, $endpoint, $method);
    logModuleCall(Config::GATEWAY_NAME, "Calling Flow Service: {$service}", $flowParams, $response, null, null);
    $urlToRedirect = $response["url"] . "?token=" . $response["token"];
    header("Location: ".$urlToRedirect);
    exit();
}catch(\Exception $e){
    logActivity('There has been an error. Code: '.$e->getCode().' Message: '.$e->getMessage());
    $errorUrl = $CONFIG['SystemURL'].'/modules/gateways/flowwp/flowwp_error.php';
    header('Location: '.$errorUrl);
    exit();
}
