<?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.            *
 ****************************************************************************/
class StripeidealModel extends PaymentModel {
    public $amount;
    public $currency;
    public $access_code; // merchant access code
    public $order_description; // order description
    public $customer_email;
    public $customer_ip; // ip adress
    public $language;
    public $command; // operation commnad (AUTHORIZATION)
    public $return_url; // back to merchant url
    
    public function process($order = '', $orderItems = ''){
        $ObjCurrency		= $this->load->model('common/CurrencyModel') ;
        parent::listPaymentSettingsValues($order['paymentSettingsGroupID']);
		
        $merchant_identifier            = $this->settingsVars["merchant_identifier"];
        $access_code			= $this->settingsVars["access_code"];   
        
        $language			= !empty($order['langLCID']) ? $order['langLCID'] :'en';      
                
        $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     = $order['masterOrderTotalAmount'];
        $userPayAmount = $payAmount*100;       
       
        if ($order['orderType'] == 'coupon') {
            $order_description = $orderItems[0]['itemName'];
        } else {
            $order_description = $order['orderDesc'];
        }
        $languageIDs = array(
            "Default" => 1,
            "All" => array(
                "0" => 1
            ),
            "Current" => 1
        );
        
        $customer_email       	= $order['billingAddress']['billingEmail'];
        $customer_ip            = $_SERVER["REMOTE_ADDR"]; // IP address of the client 
      	
        // 1- set request parameters
        $this->amount                 = $userPayAmount;
        $this->currency               = $currencyCode ;
        $this->merchant_identifier    = $merchant_identifier;
        $this->access_code            = $access_code;
        $this->order_description      = $order_description;
        $this->merchant_reference     = $order['masterOrderID'];
        //$this->return_url             = $return_url;
        $this->customer_ip            = $customer_ip;
        $this->customer_email         = $customer_email;
        $this->customer_phone         = (!empty($order['fromPG']) && $order['fromPG']!='') ? $order['billingAddress']['billingPhone'] :'';
        $this->customer_name          = (!empty($order['fromPG']) && $order['fromPG']!='') ? $order['billingAddress']['billingFirstName']." ".$order['billingAddress']['billingLastName']:'';
        $this->language               = $language;
        $this->command                = 'PURCHASE';//'TOKENIZATION';

        # Print response.         
        //echo "<pre>";print_r($order);exit;
        
	## Getting Started
	require_once('library/payment/stripe/stripe-php/init.php');

        $stripeSecretKey        = $this->settingsVars["stripe_secret_key"];
        $source                 = $order['source'];
        $currencyCodeLow        = strtolower($currencyCode);
        
        if($stripeSecretKey != '' && $customer_email !='' && $userPayAmount !='' && $currencyCodeLow != ''){
            
            \Stripe\Stripe::setApiKey($stripeSecretKey);

            try {

                $charge = \Stripe\Charge::create(array(
                  "amount" => $userPayAmount,
                  "currency" => "eur",
                  "source" => $source,
                )); 

                $chargeRes      = json_decode(json_encode($charge), true);
                $saveResp       = json_encode($charge);
                //echo "<pre>";print_r($chargeRes);exit;
                
            } catch(\Stripe\Error\InvalidRequest $e) {
              // Since it's a decline, Stripe_CardError will be caught
              //echo "<pre>";print_r($e);exit;

              $body = $e->getJsonBody();
              $err  = $body['error'];
              //echo "<pre>";print_r($err);exit;
              $errorMessage = $err['message'];
              $type = $err['type'];

              $chargeRes['status'] = 'failure';
              $saveResp       = json_encode($err);
              
//              print('Status is:' . $e->getHttpStatus() . "\n");
//              print('Type is:' . $err['type'] . "\n");
//              print('Code is:' . $err['code'] . "\n");
//              // param is '' in this case
//              print('Param is:' . $err['param'] . "\n");
//              print('Message is:' . $err['message'] . "\n");
              //$charge = false;
            } catch (Exception $e) {
                
                $body = $e->getJsonBody();
                $err  = $body['error'];
                //echo "<pre>";print_r($err);exit;
                $errorMessage = $err['message'];
                $type = $err['type'];
                
                $chargeRes['status'] = 'failure';
                $saveResp       = json_encode($err);
                
                // Something else happened, completely unrelated to Stripe
                //error_log_array($e);
                //echo "<pre>";print_r($e);exit;
               // $charge = false;
            }

        }

        
        if($chargeRes['status']=='succeeded') {
            parent::createTransaction($order, $chargeRes['id'],  $saveResp, $saveResp, "AUTH_CAPTURE", 0, $this->settingsVars["payment_method_name"], $supportedCurrencyID, $order['masterOrderTotalAmount']);
            return "Pending";
        } else {
            parent::createTransactionError($order, '',  $saveResp, $saveResp, '', "AUTH_CAPTURE", 0, $this->settingsVars["payment_method_name"]);
            $this->isError      = true;
            $this->errorMessage = "Transaction Declined: ".$errorMessage;
            return "Failure";
        }
        
    }
    
}
?>