<?php
// Ensure only POST requests are processed
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method Not Allowed');
}

// Collect and sanitize POST input
$input = filter_input_array(INPUT_POST, [
    'creditcardno' => FILTER_SANITIZE_STRING,
    'expirydate'   => FILTER_SANITIZE_STRING,
    'amount'       => FILTER_SANITIZE_NUMBER_FLOAT,
    'version'      => FILTER_SANITIZE_STRING,
    'delimdata'    => FILTER_SANITIZE_STRING,
    'relayresponse'=> FILTER_SANITIZE_STRING,
    'login'        => FILTER_SANITIZE_STRING,
    'trankey'      => FILTER_SANITIZE_STRING,
    'type'         => FILTER_SANITIZE_STRING,
    'surl'         => FILTER_SANITIZE_URL,
    'furl'         => FILTER_SANITIZE_URL
]);

// Assign to variables
$credit     = $input['creditcardno'];
$expiry     = $input['expirydate'];
$amount     = $input['amount'];
$version    = $input['version'];
$delim      = $input['delimdata'];
$relay      = $input['relayresponse'];
$login      = $input['login'];
$trankey    = $input['trankey'];
$type       = $input['type'];
$surl       = $input['surl'];
$furl       = $input['furl'];

// Validate essential data before continuing
if (empty($credit) || empty($expiry) || empty($amount) || empty($login) || empty($trankey)) {
    header("Location: $furl&msg=Missing required payment fields");
    exit;
}

// Prepare Authorize.Net POST data
$fields = http_build_query([
    'x_Version'             => $version,
    'x_Login'               => $login,
    'x_Tran_Key'            => $trankey,
    'x_Delim_Data'          => $delim,
    'x_Delim_Char'          => ',',
    'x_Type'                => $type,
    'x_Amount'              => $amount,
    'x_Card_Num'            => $credit,
    'x_Exp_Date'            => $expiry,
    'x_ADC_Relay_Response'  => $relay,
]);

// Setup cURL request
$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL            => 'https://secure.authorize.net/gateway/transact.dll',
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $fields,
    CURLOPT_TIMEOUT        => 60,
    CURLOPT_USERAGENT      => 'PHP Authorize.Net Request',
    CURLOPT_REFERER        => 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'],
]);

$response = curl_exec($ch);
$curl_error = curl_error($ch);
curl_close($ch);

// Handle cURL errors
if ($response === false) {
    error_log("cURL Error: $curl_error");
    header("Location: $furl&msg=Transaction Failed (communication error)");
    exit;
}

// Parse response
$response_fields = explode(',', $response);
$transaction_status = trim($response_fields[0] ?? '');

// Redirect based on transaction result
if ($transaction_status === '1') {
    header("Location: $surl");
    exit;
} else {
    $error_msg = rawurlencode("Card Validation Failed. Please Try Again.");
    header("Location: $furl&msg=$error_msg");
    exit;
}
?>
