<?php
use Omnipay\Omnipay;

$authorize_net_apiLoginId = get_option('authorize_net_apiLoginId', 'payments');
$authorize_net_transactionKey = get_option('authorize_net_transactionKey', 'payments');
$authorize_net_developerMode = get_option('authorize_net_testMode', 'payments');



$gateway = Omnipay::create('AuthorizeNet_AIM');
$gateway->setApiLoginId($authorize_net_apiLoginId);
$gateway->setTransactionKey($authorize_net_transactionKey);
if(intval($authorize_net_developerMode) != 0){
$gateway->setDeveloperMode(true);
}


include __DIR__.'/../lib/legacy_fields.php';


$formData = include(dirname(__DIR__).DS.'lib'.DS.'omnipay'.DS.'omnipay_populate_form_data.php');


try {
    // Send purchase request
    $response = $gateway->purchase(
        array(
            'amount'   => $place_order['amount'],
            'currency' => $place_order['currency'],
            'card'     => $formData
        )
    )->send();

    if ($response->isSuccessful()){
        $place_order['transaction_id'] = $response->getTransactionReference(); // a reference generated by the payment gateway
        $place_order['success'] = 'Your payment was successful! ' . $response->getMessage();
        $place_order['is_paid'] = 1;
        $place_order['order_completed'] = 1;

    } elseif ($response->isRedirect()) {
		$place_order['error'] = 'AuthorizeNet_AIM redirect is not supported yet';

    } else {
        $place_order['error'] = $response->getMessage();

    }
} catch (\Omnipay\Common\Exception\InvalidCreditCardException $e) {
    $msg = $e->getMessage();

    $place_order['error'] = $msg;

} catch (\Exception $e) {
    $msg = $e->getMessage();
    $place_order['error'] = $msg;


}
