/**	
 * Performs server side call payment processing
 * 
 * @param bool $subscribe				- indicates if payment is subcriptional payment
 * @param int $newTrandID				- if payment subscriptional, then $newTrandID specfies
 * 										  new transaction ID created by script
 * 
 * @return bool 						- true if payment is successful, false otherwise
 * 
 * 
 */
function moduleAcceptPayment($subscribe, $newTrandID = 0)
{
    global $providerConf;
    $errorMessage = '';
    if ($providerConf['Debug']) {
        writeDebugLog('Payment event', 'Payment start', false);
    }
    if (!isset($_POST['cart_order_id']) || !isset($_POST['order_number'])) {
        PrintErrorPage(_t('_no data given'));
        return false;
    }
    $transactionData = $_POST;
    $res = moduleValidateTransaction($transactionData, $errorMessage);
    $localTranID = (int) $transactionData['cart_order_id'];
    if ($res != 2) {
        finishTransaction($localTranID, $transactionData['order_number'], $res == 1);
    }
    if ($res == 1) {
        $purchaseRes = purchaseTransaction($localTranID, $res);
        if (!$purchaseRes) {
            $errorMessage = 'Purchase failed';
            $res = 0;
        }
    }
    processValidationResult($res, $errorMessage, $localTranID);
    return $res == 1;
}
/**	
 * Performs server side call payment processing
 * 
 * @param bool $subscribe				- indicates if payment is subcriptional payment
 * @param int $newTrandID				- if payment subscriptional, then $newTrandID specfies
 * 										  new transaction ID created by script
 * 
 * @return bool 						- true if payment is successful, false otherwise
 * 
 * 
 */
function moduleAcceptPayment($subscribe, $newTrandID = 0)
{
    global $providerConf;
    $errorMessage = '';
    if ($providerConf['Debug']) {
        writeDebugLog('Payment event', 'Payment start. Subscriptional: ' . ($subscribe ? 'true' : 'false'), false);
    }
    if ($providerConf['Param_process_type'] == 'Direct' || $providerConf['Param_process_type'] == 'IPN') {
        if (!isset($_POST['item_number']) || !isset($_POST['txn_id'])) {
            PrintErrorPage(_t('_no data given'));
            return false;
        }
        $transactionData = $_POST;
        $res = moduleValidateTransaction($transactionData, $errorMessage);
        if ($subscribe && $newTrandID) {
            $localTranID = $newTrandID;
        } else {
            $localTranID = (int) $transactionData['item_number'];
        }
        if ($res != 2) {
            if ($subscribe) {
                finishTransaction($transactionData['item_number'], 'dummy', false, 'This dummy transaction was created on subscription and contains subscriptional data.');
                finishSubscriptionTransaction($localTranID, $transactionData['item_number'], $transactionData['txn_id'], $res == 1, $transactionData['memo']);
            } else {
                finishTransaction($localTranID, $transactionData['txn_id'], $res == 1, $transactionData['memo']);
            }
        }
        if ($res == 1) {
            $purchaseRes = purchaseTransaction($localTranID, $res);
            if (!$purchaseRes) {
                $errorMessage = 'Purchase failed';
                $res = 0;
            }
        }
        processValidationResult($res, $errorMessage, $localTranID);
        return $res == 1;
    } elseif ($providerConf['Param_process_type'] == 'PDT') {
        if (!isset($_GET['tx'])) {
            PrintErrorPage(_t('_no data given'));
            return false;
        }
        $transactionData = $_GET;
        $res = moduleValidateTransaction($transactionData, $errorMessage);
        if ($subscribe && $newTrandID) {
            $localTranID = $newTrandID;
        } else {
            $localTranID = (int) $transactionData['item_number'];
        }
        if ($res != 2) {
            if ($subscribe) {
                finishTransaction($transactionData['item_number'], 'dummy', false, 'This dummy transaction was created on subscription and contains subscriptional data.');
                finishSubscriptionTransaction($localTranID, $transactionData['item_number'], $transactionData['txn_id'], $res == 1, $transactionData['memo']);
            } else {
                finishTransaction($localTranID, $transactionData['txn_id'], $res == 1, $transactionData['memo']);
            }
        }
        if ($res == 1) {
            purchaseTransaction($localTranID, $res);
        }
        processValidationResult($res, $errorMessage, $localTranID);
        return $res == 1;
    }
    return false;
}
/**
 * start checkout process
 */
function StartCheckout(&$errorMessage)
{
    global $dir;
    global $memberID;
    // defined in checkout.inc.php
    global $collectDataArr;
    global $enable_recurring;
    global $en_credits;
    global $credit2money;
    // these globals for module require call
    global $site;
    global $providerConf;
    global $checkoutFilename;
    global $checkoutURL;
    global $debugFilename;
    // if buy for credits
    if ($_REQUEST['use_credits'] == 'on' && $en_credits) {
        $amount = sprintf('%.2f', (double) $collectDataArr['amount']);
        $creditsAmount = sprintf("%.2f", (double) ($collectDataArr['amount'] * $credit2money));
        $creditBalance = getProfileCredits($memberID);
        $result = 0;
        if ($collectDataArr['checkout_action'] == 'credits') {
            $errorMessage = 'Credits couldn\'t be bought by credits';
            return false;
        }
        if ($creditBalance < $creditsAmount) {
            $result = 1000;
        } else {
            $purchaseRes = performPurchase($memberID, $collectDataArr['checkout_action'], $collectDataArr['data'], $amount, $result);
            if ($purchaseRes) {
                decProfileCredits($memberID, $creditsAmount);
                $result = 1;
            } else {
                $result = -1;
            }
        }
        $returnURL = returnURLByAction($collectDataArr['checkout_action'], $collectDataArr['data']);
        processValidationResult($result, $errorMessage, 0, $returnURL);
    } else {
        $providerID = (int) $_REQUEST['prov_id'];
        $providerRes = db_res("SELECT `Name`, `CheckoutFilename` FROM `PaymentProviders` WHERE `ID` = {$providerID} AND `Active`");
        if (!$providerRes || mysql_num_rows($providerRes) == 0) {
            $errorMessage = 'Wrong payment provider specified';
            return false;
        }
        $providerArr = mysql_fetch_assoc($providerRes);
        if (strlen(trim($providerArr['CheckoutFilename']))) {
            $checkoutFilename = $providerArr['CheckoutFilename'];
        } else {
            $checkoutFilename = $dir['checkout'] . $providerArr['Name'] . '.php';
        }
        if (!file_exists($checkoutFilename)) {
            $errorMessage = 'Checkout file not found';
            return false;
        }
        require_once $checkoutFilename;
        $validateRes = moduleValidateConfiguration($errorMessage);
        if (!$validateRes) {
            return false;
        }
        $localTranID = initiateTransaction($collectDataArr, $memberID, $providerID);
        if ($localTranID === false) {
            $errorMessage = 'Transaction initiating error';
            return false;
        }
        $subscriptionalPayment = $enable_recurring && $collectDataArr['allow_subscribe'] == 'on' && $_REQUEST['prov_recurring'] == 'on';
        if ($subscriptionalPayment) {
            $subsRes = initiateSubscription($localTranID, $collectDataArr['subscribe_days']);
            if (!$subsRes) {
                $errorMessage = 'Subscription initiating error';
                return false;
            }
        }
        $startRes = moduleStartTransaction($localTranID, $subscriptionalPayment, $collectDataArr['subscribe_days']);
        if (!$startRes) {
            $errorMessage = 'Transaction starting error';
            return false;
        }
    }
    return true;
}
/**	
 * Performs server side call payment processing
 * 
 * @param bool $subscribe				- indicates if payment is subcriptional payment
 * @param int $newTrandID				- if payment subscriptional, then $newTrandID specfies
 * 										  new transaction ID created by script
 * 
 * @return bool 						- true if payment is successful, false otherwise
 * 
 * 
 */
function moduleAcceptPayment($subscribe, $newTrandID = 0)
{
    global $providerConf;
    global $date_format;
    $errorMessage = '';
    if ($providerConf['Debug']) {
        writeDebugLog('Payment event', 'Payment start', false);
    }
    if ($providerConf['Param_implementation'] == 'AIM') {
        if (!isset($_POST['send_data']) || !isset($_POST['auth_card_num']) || !isset($_POST['auth_tran_id'])) {
            PrintErrorPage(_t('_no data given'));
            return false;
        }
        $transactionData = $_POST;
        if (!validateCheckoutData($transactionData)) {
            PrintErrorPage(_t('_no data given'));
            return false;
        }
        $localTranID = (int) $transactionData['auth_tran_id'];
        $tranRes = db_res("SELECT DATE_FORMAT(`Date`,  '{$date_format}' ) AS 'Date', `Amount`, `Currency`, `Status`, `Data`, `Description` FROM `Transactions`\r\n\t\t\t\t\t\t\t\tWHERE `ID` = {$localTranID}\r\n\t\t\t\t\t\t\t\tAND `Status` = 'pending'\r\n\t\t\t\t\t\t\t\tAND `IDProvider` = {$providerConf['ID']}");
        if (!$tranRes || mysql_num_rows($tranRes) == 0) {
            return false;
        }
        $tranArr = mysql_fetch_assoc($tranRes);
        $tranData = transStringToData($tranArr['Data']);
        $postURL = 'https://secure.authorize.net/gateway/transact.dll';
        $postParameters = "x_login={$providerConf['Param_x_login']}";
        $postParameters .= "&x_tran_key={$providerConf['Param_x_tran_key']}";
        $postParameters .= "&x_version=3.1";
        $postParameters .= "&x_method=CC";
        $postParameters .= "&x_type=AUTH_CAPTURE";
        $postParameters .= "&x_amount=" . sprintf("%.2f", (double) $tranArr['Amount']);
        $postParameters .= "&x_invoice_num={$localTranID}";
        $postParameters .= "&x_description={$tranArr['Description']}";
        $postParameters .= "&x_relay_response=FALSE";
        $postParameters .= "&x_email_customer=FALSE";
        $postParameters .= "&x_delim_data=TRUE";
        $postParameters .= "&x_delim_char={$providerConf['Param_x_delim_char']}";
        $postParameters .= "&x_encap_char={$providerConf['Param_x_encap_char']}";
        $postParameters .= "&x_card_num={$transactionData['auth_card_num']}";
        $postParameters .= "&x_exp_date={$transactionData['auth_expire_month']}-{$transactionData['auth_expire_year']}";
        $postParameters .= "&x_cust_id={$tranData['memberID']}";
        $postParameters .= "&x_test_request=" . ($providerConf['Mode'] == 'live' ? 'FALSE' : 'TRUE');
        $response = sendCurlRequest($postURL, $postParameters);
        if ($providerConf['Debug']) {
            writeDebugLog('AIM request response', $response, false);
        }
        $responseArr = explode($providerConf['Param_x_delim_char'], $response);
        $encapChar = $providerConf['Param_x_encap_char'];
        if ($encapChar == '\'' || $encapChar == '\\') {
            $encapChar = '\\' . $encapChar;
        }
        array_walk($responseArr, create_function('&$arg', "\$arg = trim(\$arg, '{$encapChar}');"));
        $transactionData = $responseArr;
        $res = moduleValidateTransaction($transactionData, $errorMessage);
        $localTranID = (int) $transactionData[7];
        if ($res != 2) {
            finishTransaction($localTranID, $transactionData[6], $res == 1);
        }
        if ($res == 1) {
            $purchaseRes = purchaseTransaction($localTranID, $res);
            if (!$purchaseRes) {
                $errorMessage = 'Purchase failed';
                $res = 0;
            }
        }
        processValidationResult($res, $errorMessage, $localTranID);
        return $res == 1;
    } elseif ($providerConf['Param_implementation'] == 'SIM') {
        if (!isset($_POST['x_response_code']) || !isset($_POST['x_invoice_num'])) {
            PrintErrorPage(_t('_no data given'));
            return false;
        }
        $transactionData = $_POST;
        $res = moduleValidateTransaction($transactionData, $errorMessage);
        $localTranID = (int) $transactionData['x_invoice_num'];
        if ($res != 2) {
            finishTransaction($localTranID, $transactionData['x_trans_id'], $res == 1);
        }
        if ($res == 1) {
            $purchaseRes = purchaseTransaction($localTranID, $res);
            if (!$purchaseRes) {
                $errorMessage = 'Purchase failed';
                $res = 0;
            }
        }
        processValidationResult($res, $errorMessage, $localTranID);
        return $res == 1;
    }
    return false;
}