<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/
//
//$Id: CaledonModel.php, v 1.0 2011/06/14 20:52:11
//
class CaledonModel extends PaymentModel
{
    public function process($order = '', $postForm = '', $orderItems = '')//payment collection through payment gateway
    {
        $paymentStatus = "";
        parent::listPaymentSettingsValues($postForm['paymentSettingsGroupID']);
        $termID  = $this->settingsVars["TERMID"];
        $payType = $this->settingsVars['TYPE'];
        if ($postForm['authValue'] == "AUTH_ONLY" || $postForm['authValue'] == "Authorization") {
            $payType = "P";
        } else {
            $payType = "S";
        }
        $paymentURL      = $this->settingsVars['payment_gateway_url'];
        $ddlExpiryMonth  = $postForm['expMonth'];
        $ddlExpiryYear   = $postForm['expYear'];
        $payAmount       = $order['masterOrderTotalAmount'];
        $userPayAmount   = number_format($payAmount, 2);
        $txtCCNumber     = $postForm['creditCardNumber'];
        $cardExp         = $ddlExpiryMonth . $ddlExpiryYear;
        $refCode         = $order["masterOrderID"];
        $card            = $txtCCNumber;
        $paymentURL      = "$paymentURL?TERMID=$termID&CARD=$txtCCNumber&EXP=$cardExp&AMT=$userPayAmount&REF=$refCode&TYPE=$payType";
        $paymentResponse = file_get_contents($paymentURL);
        $arrResponse     = explode('CODE', $paymentResponse);
        if (count($arrResponse) > 0) {
            $intResponse = $arrResponse[1];
            if ($intResponse == "=0000") {
                $paymentStatus = 'Pending';
                $lblResult     = $arrResponse[0];
                $transactionID = $intResponse;
				$userPayAmount = $order['masterOrderTotalAmount'];
                if ($this->settingsVars["payment_gateway_charge_percent"] != '') {
                    $paymentGatewayCharge = ($userPayAmount * $this->settingsVars["payment_gateway_charge_percent"]) / 100;
                }
                $paymentGatewayCharge = $paymentGatewayCharge + $this->settingsVars["payment_gateway_charge"];
                $paymentMethodName    = $this->settingsVars["payment_method_name"];
                if ($postForm['authValue'] == 'Authorization') {
                    $authOnly = 'AUTH_ONLY';
                } else {
                    $authOnly = 'AUTH_CAPTURE';
                }
                parent::createTransaction($postForm, $order, $transactionID, str_replace("~", "\n", $lblResult), "", $authOnly, $paymentGatewayCharge, $paymentMethodName,$supportedCurrencyID,$payAmount);
                if ($order['store_cc_info'] == 'Yes') {
                    parent::saveCCdata($postForm, $order["userID"]);
                }
                $this->isError      = true;
                $this->errorMessage = "";
            } else {
                $paymentStatus = 'Failure';
                $lblResult     = $arrResponse[0];
                $intLen        = strlen($lblResult);
                $pos           = strpos($lblResult, '&');
                if ($pos !== false) {
                    $lblResult = str_replace("&", ".", $lblResult);
                }
                $lblResult          = substr($lblResult, 5, $intLen);
                $this->isError      = true;
                $this->errorMessage = "We are sorry, but this transaction has been declined.<br>Payment gateway response: " . $lblResult;
            }
        } else {
            $lblResult          = "Error: An invalid response was recieved from the payment gateway.";
            $paymentStatus      = 'Failure';
            $this->isError      = true;
            $this->errorMessage = "We are sorry, but this transaction has been declined.<br>Payment gateway response: " . $lblResult;
        }
        return $paymentStatus;
        exit;
    }
	
    public function processCustom($order = '', $postForm = '')//complete the auth only transactions
    {
        $ObjUser = new UserModel();
        parent::listPaymentSettingsValues($order['paymentSettingsGroupID']);
        $getPaymentTransactionDetails = $this->getPaymentTransactionDetails($order["masterOrderID"]);
        $this->isError                = false;
        //check is transaction completed
        if ($order["paymentType"] != "AUTH_ONLY" || $order["paymentStatus"] == 'Received') {
            $this->isError      = true;
            $this->errorMessage = "Transaction already completed";
            return false;
        }
        //get captured total amount & x_trans_id
        $capturedTotalAmount = $order["finalAmountToPay"];
        $payAmount           = $capturedTotalAmount;
        $transactionID       = $order["transactionID"];
        $taxAmount           = $order["finalTaxAmount"];
        $userPayAmount       = $payAmount + $taxAmount;
        $userPayAmount       = number_format($userPayAmount, 2);
        $userCCInfo          = $ObjUser->getUserCCInfo($order['userID']);
        $ddlExpiryMonth      = $userCCInfo['expMonth'];
        $ddlExpiryYear       = $userCCInfo['expYear'];
        $cardExp             = $ddlExpiryMonth . $ddlExpiryYear;
        $refCode             = $order["masterOrderID"];
        $payType             = "C";
        $paymentURL          = $this->settingsVars['payment_gateway_url'];
        $termID              = $this->settingsVars["TERMID"];
        $paymentURL          = "$paymentURL?TERMID=$termID&CARD=0&EXP=$cardExp&AMT=$userPayAmount&REF=$refCode&TYPE=$payType";
        $paymentResponse     = file_get_contents($paymentURL);
        $arrResponse         = explode('CODE', $paymentResponse);
        if (count($arrResponse) > 0) {
            $intResponse = $arrResponse[1];
            if ($intResponse == "=0000") {
                $paymentStatus = 'Success';
                $lblResult     = $arrResponse[0];
                $transactionID = $intResponse;
                if ($this->settingsVars["payment_gateway_charge_percent"] != '') {
                    $paymentGatewayCharge = ($userPayAmount * $this->settingsVars["payment_gateway_charge_percent"]) / 100;
                }
                $paymentGatewayCharge = $paymentGatewayCharge + $this->settingsVars["payment_gateway_charge"];
                $paymentMethodName    = $this->settingsVars["payment_method_name"];
                $order['orderStatus'] = 'Completed';
                parent::createTransaction($postForm, $order, $transactionID, "ORDER TYPE: PRIOR_AUTH_CAPTURE\n\n" . str_replace("~", "\n", $lblResult), "", "AUTH_CAPTURE", $paymentGatewayCharge, $paymentMethodName,$supportedCurrencyID,$payAmount);
                if ($order['store_cc_info'] == 'Yes') {
                    parent::saveCCdata($postForm, $order["userID"]);
                }
                $this->isError      = true;
                $this->errorMessage = "";
            } else {
                $paymentStatus = 'Failure';
                $lblResult     = $arrResponse[0];
                $intLen        = strlen($lblResult);
                $pos           = strpos($lblResult, '&');
                if ($pos !== false) {
                    $lblResult = str_replace("&", ".", $lblResult);
                }
                $lblResult          = substr($lblResult, 5, $intLen);
                $this->isError      = true;
                $this->errorMessage = "We are sorry, but this transaction has been declined.<br>Payment gateway response: " . $lblResult;
            }
        } else {
            $lblResult          = "Error: An invalid response was recieved from the payment gateway.";
            $paymentStatus      = 'Failure';
            $this->isError      = true;
            $this->errorMessage = "We are sorry, but this transaction has been declined.<br>Payment gateway response: " . $lblResult;
        }
        return $paymentStatus;
    }
	
    public function processRefund($order = '', $postValues = '')//payment refunding process
    {
        $ObjRefund           = new RefundModel();
        $masterOrderID       = $postValues['masterOrderID'];
        $refundTransactionID = $postValues['keyRefundTransactionID'];
        parent::listPaymentSettingsValues($postValues['paymentSettingsGroupID']);
        $termID         = $this->settingsVars["TERMID"];
        $payType        = 'R'; 
        $paymentURL     = $this->settingsVars['payment_gateway_url'];
        $ddlExpiryMonth = $postValues['expMonth'];
        $ddlExpiryYear  = $postValues['expYear'];
        $ddlExpiryYear  = $ddlExpiryYear[2] . $ddlExpiryYear[3];
        $cardExp        = $ddlExpiryMonth . $ddlExpiryYear;
        $txtCCNumber    = $postValues['creditCardNumber'];
        $refundAmount   = $order['masterOrderTotalAmount'];
        $refundAmount   = (number_format($refundAmount, 2)) * 100;
        $refCode        = urlencode($postValues['apiPaymentTransactionID']);
        $paymentURL     = "$paymentURL?TERMID=$termID&CARD=$txtCCNumber&EXP=$cardExp&AMT=$refundAmount&REF=$refCode&TYPE=$payType";
        $refundResponse = file_get_contents($paymentURL);
        $arrResponse    = explode('CODE', $refundResponse);
        if (count($arrResponse) > 0) {
            if ($arrResponse[1] == "=0000") {
                $refundStatus                    = 'Success';
                $arrXnResponse['transactionID']  = '0000';
                $arrXnResponse['refundResponse'] = $refundResponse;
                $arrXnResponse['refundAmount']   = trim(substr($refundResponse, 11, -10));
                $resUpdateRefund                 = $ObjRefund->updateRefundTransaction('', $refundTransactionID, $arrXnResponse,$masterOrderID);
                $this->isError                   = true;
                $this->errorMessage              = "";
            } else {
                $refundStatus                    = 'Error';
                $arrXnResponse['transactionID']  = '';
                $arrXnResponse['refundResponse'] = $refundResponse;
                $arrXnResponse['refundAmount']   = '';
                $resUpdateRefund                 = $ObjRefund->updateRefundTransaction('', $refundTransactionID, $arrXnResponse,$masterOrderID);
                $this->isError                   = true;
                $this->errorMessage              = "This transaction has been declined.<br>Payment gateway response: " . $lblResult;
            }
        } else {
            $lblResult          = "Error: An invalid response was recieved from the payment gateway.";
            $refundStatus       = 'Failure';
            $this->isError      = true;
            $this->errorMessage = "This transaction has been declined.<br>Payment gateway response: " . $lblResult;
        }
        return !$this->isError;
        exit;
    }
}