<?php

use Mtc\Shop\Order\Protx;

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';
require SITE_PATH . '/shop/checkout/server/function.sagepay.php';

$payment = Protx::query()
    ->whereNull('captured_at')
    ->where('order_id', request()->input('order_id'))
    ->find(request()->input('transaction_id'));

if (!$payment) {
    header('Location: ' . back()->getTargetUrl());
    exit;
}

// $strReleaseUrl is defined in function.sagepay
$endpoint = $strAbortURL;
$post_values = [
    'VPSProtocol' => (string)SAGEPAY_PROTOCOL,
    'TxType' => 'ABORT',
    'Vendor' => SAGEPAY_VENDOR,
    'VendorTxCode' => $payment->VendorTxCode,
    'VPSTxId' => $payment->VPSTxId,
    'TxAuthNo' => $payment->TxAuthNo,
    'ReleaseAmount' => $payment->Amount,
    'SecurityKey' => $payment->SecurityKey,
];

$prepared_command = implode('&', array_map(function ($value, $key) {
    return "$key=$value";
}, $post_values, array_keys($post_values)));

$response = requestPost($endpoint, $prepared_command);

if ($response['Status'] === 'OK') {
    $payment->captured_at = \Carbon\Carbon::now();
    $payment->save();
    $_SESSION['message'] = $response['StatusDetail'];
    $order = new \Order(request()->input('order_id'));
    $order->updateStatus(\Mtc\Shop\Order::STATUS_CANCELLED);
} else {
    $_SESSION['error'] = $response['StatusDetail'];
}

header('Location: ' . back()->getTargetUrl());
exit;
