<?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: PayUModel.php, v 1.0 2011/06/14 20:52:11
//
class EbsDebitCardModel extends PaymentModel {
    var $fields = array(); // array holds the fields to submit to vtn
    function addField($field, $value) {
        // adds a key=>value pair to the fields array, which is what will be 
        // sent to vtn as POST variables.  If the value is already in the 
        // array, it will be overwritten.
        $this->fields["$field"] = $value;
    }
    
    public function process($order = '', $orderItems = '', $postForm = ''){
        $ObjCurrency = new CurrencyModel();
        $ObjCountry  = new CountryModel();
        $ObjState    = new StateModel();
        parent::listPaymentSettingsValues($order['paymentSettingsGroupID']);
        $accountID       = $this->settingsVars['payment_account_id'];
        $secretKey       = $this->settingsVars["payment_secret_key"];
  
        $currencyArr     = '';
        $paymentCurrency = $this->settingsVars["payment_currency"];
        if ($paymentCurrency != '') {
            $paymentCurrency = str_replace(", ", ",", $paymentCurrency);
            $currencyArr     = explode(",", $paymentCurrency);
        }
        if (count($currencyArr) < 1) {
            $this->isError      = true;
            $this->errorMessage = "Currency not configured , Please contact the site admin";
            return false;
        } else {
            $currencyFlag             = false;
            $purchasedCurrencyDetails = $ObjCurrency->getCurrencyByCurrencyID($order["purchasedCurrency"]);
            $currencyCode             = $purchasedCurrencyDetails['currencyCode'];
            $systemCurrencies         = $ObjCurrency->listCurrencyCodes();
            if (!in_array($purchasedCurrencyDetails['currencyCode'], $currencyArr)) {
                foreach ($systemCurrencies as $key => $currency) {
                    if (in_array($currency['currencyCode'], $currencyArr)) {
                        $currencyFlag          = true;
                        $supportedCurrencyCode = $currency['currencyCode'];
                        $supportedCurrencyID   = $currency['currencyID'];
                        break;
                    }
                }
                if ($currencyFlag == true) {
                    $payAmount    = $ObjCurrency->convertValueCustom($payAmount, $order["purchasedCurrency"], $supportedCurrencyID);
                    $currencyCode = $supportedCurrencyCode;
                } else {
                    $this->isError      = true;
                    $this->errorMessage = "Currency not configured , Please contact the site admin";
                    return false;
                }
            }
        }
       
        $payAmount     = number_format($order['orderTotalAmount'],2);  
        $payAmount     = str_replace(",", "", $payAmount);
        $randomNumber  = $this->getRandomCode(8, 'Alphanumerics');
        //$txnid=$order['orderID'];
        $txnid         = $randomNumber . $order['masterOrderID'];
        if ($order['orderType'] == 'coupon') {
            $productinfo = $orderItems[0]['itemName'];
        } else {
            $productinfo = $order['orderDesc'];
        }
        $languageIDs = array(
            "Default" => 1,
            "All" => array(
                "0" => 1
            ),
            "Current" => 1
        );
        $country     = $ObjCountry->getCountryDetails($order['billingAddress']['billingCountry'], $languageIDs);
        $countryCode = $country['countryIsoA3'];
        if ($order['orderType'] != 'coupon') {
            $country     = $ObjCountry->getCountryDetails($order['shippingAddress']['shippingCountryID'], $languageIDs);
            $ship_country= $country['countryIsoA3'];
        } else {
            $ship_country= $countryCode;
        }
          
        if ($order['billingAddress']['billingState'] > 0) {
            $getStateDetails = $ObjState->getStateDetails($languageIDs, $order['billingAddress']['billingState']);
            $stateName       = $getStateDetails['stateName'];
        } else {
            $stateName = $order['billingAddress']['billingProvince'];
        }
        if ($order['orderType'] != 'coupon') {
            if ($order['shippingAddress']['shippingStateID'] > 0) {
                $getStateDetails = $ObjState->getStateDetails($languageIDs, $order['shippingAddress']['shippingStateID']);
                $ship_state      = $getStateDetails['stateName'];
            } else {
                $ship_state      = $order['shippingAddress']['shippingProvince'];
            }
        } else {
            $ship_state          = $stateName;
        }    
         
           
        $name                    = $order['billingAddress']['billingFirstName']." ".$order['billingAddress']['billingLastName'];        
        $address                 = trim($order['billingAddress']['billingAddress'], '"');
        //$address                 = !empty($order['billingAddress']['billingAddress1']) ? $address." ".$order['billingAddress']['billingAddress1']:'';
        $city                    = $order['billingAddress']['billingCity'];
        $state                   = $stateName;        
        $email                   = $order['billingAddress']['billingEmail'];
        $phone                   = $order['billingAddress']['billingPhone'];
        $billingZip              = $order['billingAddress']['billingZip'];
        $ship_address            = ($order['orderType'] != 'coupon')?$order['shippingAddress']['shippingAddress']:$address;
        $ship_address = trim($ship_address, '"');
        $ship_city               = ($order['orderType'] != 'coupon')?$order['shippingAddress']['shippingCity']:$city;
        $ship_postal_code        = ($order['orderType'] != 'coupon')?$order['shippingAddress']['shippingZip']:$billingZip;
        $ship_phone              = ($order['orderType'] != 'coupon')?$order['shippingAddress']['shippingPhone']:$phone;
        $ship_name               = ($order['orderType'] != 'coupon')?$order['shippingAddress']['shippingFname']." ".$order['shippingAddress']['shippingLname']:$name;              
        
        $channel                = 0;
        $mode                   = ($this->settingsVars['payment_test']=='On')?'TEST':'LIVE';
        $itemsArray='';
        if (!empty($orderItems)) {
            foreach ($orderItems as $key => $ordItem) {
                $orderGiveAsGift = '';
                if ($ordItem['orderGiveAsGift'] == 'Yes') {
                    $orderGiveAsGift = ' (As Gift)';
                }
                $fldName = ($order['orderType'] == 'product') ? 'productOptionName' : 'itemName';
                $itemsArray.= htmlspecialchars(preg_replace("/[^a-zA-Z0-9 ]/", "", substr($ordItem[$fldName], 0, 110))) . $orderGiveAsGift . " Quantity - " . $ordItem['orderItemQuantity'] . ", ";
            }
        }
        $itemsArray =    substr($itemsArray, 0, 250);
        $currencyCode = 'INR';
        $_POST = array();
        $_POST['account_id']    = $accountID;
        $_POST['address']       = $address;
        $_POST['amount']        = $payAmount;
        $_POST['bank_code']     = '';
        $_POST['card_brand']    = '';        
        $_POST['channel']       = $channel;
        $_POST['city']          = $city;
        $_POST['country']       = $countryCode;
        $_POST['currency']      = $currencyCode;
        $_POST['description']   = $itemsArray;        
        $_POST['email']         = $email;
        $_POST['emi']           = '';
        $_POST['mode']          = $mode;
        $_POST['name']          = $name;
        $_POST['page_id']       = '';
      //  $_POST['payment_mode']  = 2;
        $_POST['payment_mode']  = $order['payment_mode'];
        $_POST['payment_option']= '';        
        $_POST['phone']         = $phone;
        $_POST['postal_code']   = $billingZip;
        $_POST['reference_no']  = $order['masterOrderID'];
        $_POST['return_url']    = $order['returnURL'];
        $_POST['ship_address']  = $ship_address;
        $_POST['ship_city']     = $ship_city;
        $_POST['ship_country']  = $ship_country;
        $_POST['ship_name']     = $ship_name;
        $_POST['ship_phone']    = $ship_phone;
        $_POST['ship_postal_code']  = $ship_postal_code;
        $_POST['ship_state']    = $ship_state;        
        $_POST['state']         = $stateName;
        ksort($_POST);
//        echo '<pre>';
//        print_r($_POST);
//        print_r($order);
//        echo $secretKey;
  //      exit; 
        
        foreach ($_POST as $key => $value){
                if (strlen($value) > 0) {
                        $secretKey .= '|'.$value;
                }
        }
        if (strlen($secretKey) > 0) {
                $secure_hash = strtoupper(hash("sha512",$secretKey));//for SHA512
             //   $secure_hash = strtoupper(hash("sha1",$hashData));//for SHA1
             //   $secure_hash = strtoupper(md5($hashData));//for MD5
        }        
      
        $payment_test    = $this->settingsVars['payment_test'];
        if($payment_test == 'On')
        $action    = $this->settingsVars['payment_gateway_url_test'];
        else
        $action    = $this->settingsVars['payment_gateway_url'];
        
        
        echo '<html><body>                     	
                      <form method="post" name="ebsForm" action="' . $action . '">    
                        <input type="hidden" name="account_id" value="' . $accountID . '" />  
                        <input type="hidden" name="address" value="' . $address . '" />      
                        <input type="hidden" name="amount" value="' . $payAmount . '" />  
                        <input type="hidden" name="bank_code" value="" />  
                        <input type="hidden" name="card_brand" value="" />      
                        <input type="hidden" name="channel" value="' . $channel . '" />  
                        <input type="hidden" name="city" value="' . $city . '" />
                        <input type="hidden" name="country" value="' . $countryCode . '" /> 
                        <input type="hidden" name="currency" value="'.$currencyCode.'" />
                        <input type="hidden" name="description"  value="' . $itemsArray . '" />                          
                        <input type="hidden" name="email" value="' . $email . '" />
                        <input type="hidden" name="emi" value="" />    
                        <input type="hidden" name="mode" value="' . $mode . '" />
                        <input type="hidden" name="name" value="' . $name . '" />    
                        <input type="hidden" name="page_id" value="" />
                        <input type="hidden" name="payment_mode" value="'.$order['payment_mode'].'" />
                        <input name="payment_option" type="hidden" value="" />
                        <input type="hidden" name="phone" value="'.$phone.'" />
                        <input type="hidden" name="postal_code" value="' . $billingZip . '" />    
                        <input type="hidden" name="reference_no" value="' . $order['masterOrderID'] . '"/>                        
                        <input type="hidden" name="return_url" value="' . $order['returnURL'] . '" />
                        <input type="hidden" name="ship_address" value="' . $ship_address . '" /> 
                        <input type="hidden" name="ship_city" value="' . $ship_city . '" /> 
                        <input type="hidden" name="ship_country" value="' . $ship_country . '" />     
                        <input type="hidden" name="ship_name" value="' . $ship_name . '" />     
                        <input type="hidden" name="ship_phone" value="' . $ship_phone . '" />     
                        <input type="hidden" name="ship_postal_code" value="' . $ship_postal_code . '" />          
                        <input type="hidden" name="ship_state" value="'.$ship_state.'"/>  
                        <input type="hidden" name="state" value="'.$stateName.'"/>
                        <input type="hidden" name="secure_hash" value="' . $secure_hash . '" /> 
			<script language="javascript" type="text/javascript">                           
                            document.ebsForm.submit();                            
			</script>
                        </form>
		</body></html>';
        exit;
    }
    public function getResponse($order = '',$response='') {
        parent::listPaymentSettingsValues($order['paymentSettingsGroupID']);
        $accountID       = $this->settingsVars['payment_account_id'];
        $secretKey       = $this->settingsVars["payment_secret_key"];
        
        $sh              = $response['SecureHash'];	
        $params          = $secretKey;        
//        ksort($response);
//        foreach ($response as $key => $value){
//            if (strlen($value) > 0 && $key!='SecureHash') {
//                    $params .= '|'.$value;
//            }
//        }	
//        
//        //$hashValue = strtoupper(md5($params));//for MD5
//        //$hashValue = strtoupper(hash("sha1",$params));//for SHA1
//        
//        $hashValue = strtoupper(hash("sha512",$params));// for SHA512
//  	if($sh!=$hashValue) {
//            
//            $this->isError = true;
//            $this->errorMessage = $response['ResponseMessage'];
//            return !$this->isError;
//        } else {
//             
//            $this->isError = false;
//            $this->errorMessage = "";
//            return "Pending";
//        }
        if($order['mobileApp']!="Yes"){
        $sh              = $response['SecureHash'];	
        $params          = $secretKey;        
        ksort($response);
        foreach ($response as $key => $value){
            if (strlen($value) > 0 && $key!='SecureHash') {
                    $params .= '|'.$value;
            }
        }	
        
        //$hashValue = strtoupper(md5($params));//for MD5
        //$hashValue = strtoupper(hash("sha1",$params));//for SHA1
        
        $hashValue = strtoupper(hash("sha512",$params));// for SHA512
        }
        if($order['mobileApp']=='Yes'){
            $sysMD5 = md5($accountID."|".$secretKey."|".number_format($order['orderTotalAmount'], 2, '.', ''));
            if($sysMD5 == $order['appSecureHash']){
                $this->isError = false;
                $this->errorMessage = "";
                return "Pending";
            }else{
                $this->isError = true;
                $this->errorMessage = $response['ResponseMessage'];
                return !$this->isError;
            }
        }else{
            if($sh!=$hashValue || $response['ResponseCode']!=0) {
            
            $this->isError = true;
            $this->errorMessage = $response['ResponseMessage'];
            return !$this->isError;
            } else {

                $this->isError = false;
                $this->errorMessage = "";
                return "Pending";
            }	
        }
    }
    public function getRandomCode($length, $type) {
        if ($type == 'Alphanumerics')
            $characters = '23456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        else
            $characters = '0123456789';
        $string       = '';
        $stringLength = strlen($characters) - 1;
        for ($p = 0; $p < $length; $p++) {
            $string .= $characters[mt_rand(0, $stringLength)];
        }
        return $string;
    }
    public function processRefund($order = '', $postValues = '', $orderItems = '') {
        $ObjPayment          = new PaymentModel();
        $ObjRefund           = new RefundModel();
        $pxPay               = $ObjPayment->listPaymentSettingsValues($postValues['paymentSettingsGroupID']);
        $TxnRef              = urlencode($postValues['apiPaymentTransactionID']);
        $orderID             = $postValues['masterOrderID'];
        return 'Success';
    
    }   
    //Function to Process curl
    public function processCurl($postData, $postUrl) {
        $c = curl_init($postUrl);
        curl_setopt($c, CURLOPT_VERBOSE, 0);
        curl_setopt($c, CURLOPT_HEADER, 0);
        curl_setopt($c, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($c, CURLOPT_POST, 1);
        curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 1);
        if (!ini_get('safe_mode'))
            set_time_limit(3000);
        $buffer = curl_exec($c);
        if (curl_errno($c) > 0) {
            $this->isError      = true;
            $this->errorMessage = curl_error($c);
            return false;
        }
        return !$buffer ? false : $buffer;
    }
    //End of function
    
}


?>