<?php

require_once 'config.php';
use OptimalPayments\OptimalApiClient;
use OptimalPayments\Environment;
use OptimalPayments\CustomerVault\Profile;
use OptimalPayments\CustomerVault\Address;
use OptimalPayments\CustomerVault\Card;
use OptimalPayments\CardPayments\Authorization;
if ($_POST) {
    $client = new OptimalApiClient($optimalApiKeyId, $optimalApiKeySecret, Environment::TEST, $optimalAccountNumber);
    try {
        $profile = $client->customerVaultService()->createProfile(new Profile(array("merchantCustomerId" => $_POST['merchant_customer_id'], "locale" => "en_US", "firstName" => $_POST['first_name'], "lastName" => $_POST['last_name'], "email" => $_POST['email'])));
        $address = $client->customerVaultService()->createAddress(new Address(array("nickName" => "home", 'street' => $_POST['street'], 'city' => $_POST['city'], 'state' => $_POST['state'], 'country' => $_POST['country'], 'zip' => $_POST['zip'], "profileID" => $profile->id)));
        $card = $client->customerVaultService()->createCard(new Card(array("nickName" => "Default Card", 'cardNum' => $_POST['card_number'], 'cardExpiry' => array('month' => $_POST['card_exp_month'], 'year' => $_POST['card_exp_year']), 'billingAddressId' => $address->id, "profileID" => $profile->id)));
        $auth = $client->cardPaymentService()->authorize(new Authorization(array('merchantRefNum' => $_POST['merchant_ref_num'], 'amount' => $_POST['amount'] * $currencyBaseUnitsMultiplier, 'settleWithAuth' => true, 'card' => array('paymentToken' => $card->paymentToken))));
        die('Payment successful! ID: ' . $auth->id);
    } catch (OptimalPayments\NetbanxException $e) {
        echo '<pre>';
        var_dump($e->getMessage());
        if ($e->fieldErrors) {
            var_dump($e->fieldErrors);
        }
        if ($e->links) {
            var_dump($e->links);
        }
        echo '</pre>';
    } catch (\OptimalPayments\OptimalException $e) {
        var_dump($e->getMessage());
    }
}