<?php
/**
 * @version $Id: standard.php 444 2015-06-01 08:24:11Z michal $
 * @package DJ-Catalog2
 * @copyright Copyright (C) 2012 DJ-Extensions.com LTD, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 * @developer Michal Olczyk - michal.olczyk@design-joomla.eu
 *
 * DJ-Catalog2 is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * DJ-Catalog2 is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with DJ-Catalog2. If not, see <http://www.gnu.org/licenses/>.
 *
 */

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

//jimport('joomla.plugin.plugin');

class plgDjcatalog2paymentMellat extends JPlugin {
	
	protected $currency;
	
	public function __construct(&$subject, $config = array())
	{
		parent::__construct($subject, $config);
        $cparams = JComponentHelper::getParams('com_djcatalog2');
        $this->currency = $cparams->get('cart_currency', 'USD');
		$this->debug = $this->params->get('debug', 0);
		//$this->loadLanguage();
		
		//require_once JPATH_ROOT.'/plugins/djcatalog2payment/mellat/lib/paypal_ipn.php';
	}
	
	protected function isAllowed($plgInfo, $type = 'djcatalog2payment') {
		return (bool)($plgInfo->plugin == $this->_name && $this->_type == $type);
	}
	
	public function onContentPrepareForm($form, $data) {
		if ($form->getName() != 'com_djcatalog2.payment') {
			return;
		}
		
		$plugin = '';
		
		if (!empty($data) && !empty($data->plugin)) {
			$plugin = $data->plugin;
		} else {
			$jform = JFactory::getApplication()->input->get('jform', array(), 'array');
			if (!empty($jform) && isset($jform['plugin'])) {
				$plugin = $jform['plugin'];
			}
		}
		
		if ($plugin != $this->_name) {
			return true;
		}
		
		return $form->loadFile(dirname(__FILE__).DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'configuration.xml', false);
	}
	
	public function onDJC2BeforeSaveOrder($context, $table, $isNew, $plgInfo) {
		if ($context != 'com_djcatalog2.checkout.payment' || !$this->isAllowed($plgInfo)) {
			return;
		}
	}
	
	public function onDJC2AfterSaveOrder($context, $table, $isNew, $plgInfo) {
		if ($context != 'com_djcatalog2.checkout.payment' || !$this->isAllowed($plgInfo)) {
			return;
		}
	}
	
	public function onDJC2CheckoutDetailsDisplay($context, $plgInfo) {
		if ($context != 'com_djcatalog2.checkout.payment' || !$this->isAllowed($plgInfo)) {
			return;
		}
		
		$html = '';
		if (trim(strip_tags($plgInfo->description)) != '' ) {
			$html = '<h4>'.$plgInfo->name.'</h4>';
			$html .= $plgInfo->description;
		}
		return $html;
	}
	
	public function onDJC2OrderDetailsDisplay($context, $order, $plgInfo) {
		if ($context != 'com_djcatalog2.order.payment' || !$this->isAllowed($plgInfo)) {
			return;
		}
        
		$app = JFactory::getApplication();
		
        $message = '';
        if ($app->input->get('view') == 'order' && $app->input->get('error')) {
            $message = JText::_('پرداخت شما تایید نشده است . مجدد اقدام نمایید');
        } else if ($app->input->get('success') == '1') {
            $message = JText::_('پس از پرداخت ، سفارش شما تایید خواهد شد');
        }
        
        if ($order->status != 'A' && $order->status != 'N') {
            return;
        }
		
		$paymentUrl = JRoute::_('index.php?option=com_djcatalog2&task=paymentProcess&oid='.$order->id.'&plg='.$plgInfo->plugin.'&plgid='.$plgInfo->id);
		
		$html = '<div class="paypalinfo">';
		
		if ($message) {
            $html .= '<p class="paypalalert">'.$message.'</p>';
		} else if ($app->input->get('finished') == '1' ) {
        	$app->redirect(JRoute::_('index.php?option=com_djcatalog2&task=paymentProcess&oid='.$order->id.'&plg='.$plgInfo->plugin.'&plgid='.$plgInfo->id, false), 302);
		} 
		
        
		$html .= '<p class="paypalmessage">';
        $html .= JText::_('پرداخت خود را انجام دهید');
        $html .= '</p>';
        $html .= '<p class="paypalbutton">';
        $html .= '<a href="'.$paymentUrl.'" class="paypalbtn btn btn-primary">'.JText::_('پرداخت با درگاه بانک ملت').'</a>';
        $html .= '</p>';
		$html .= '</div>';
		
		return $html;
	}
    
    public function onDJC2PaymentProcess($context, $order, $plgInfo) {
        if ($context != 'com_djcatalog2.order.payment' || !$this->isAllowed($plgInfo)) {
            return;
        }
        
        $terminalId = $plgInfo->params->get('terminalid');
		$userName = $plgInfo->params->get('username');
		$userPassword = $plgInfo->params->get('userpassword');
		$payerId = 0;
		$localDate = date("Ymd");
        $localTime = date("His");
		$additionalData = '';
		
		if (empty($emailId)) {
			throw new Exception(JText::_('تنظیمات بانکی انجام نشده است'), 400);
		}
		
		$app = JFactory::getApplication();
		$websiteName = $app->get('sitename', JURI::base());
		
		
		
		//$return = JRoute::_(DJCatalogHelperRoute::getOrderRoute($order->id).'&success=1', false, (JUri::getInstance()->isSSL() ? 1 : -1));
		//$cancel_return = JRoute::_(DJCatalogHelperRoute::getOrderRoute($order->id).'&error=1', false, (JUri::getInstance()->isSSL() ? 1 : -1));
		$notify_url = JRoute::_(DJCatalogHelperRoute::getCategoryRoute(0).'&task=paymentResponse&plg='.$plgInfo->plugin.'&plgid='.$plgInfo->id.'&oid='.$order->id, false, (JUri::getInstance()->isSSL() ? 1 : -1));
		
		//$cancel_return .= '&ts=' . time();
		$notify_url .= '&ts=' . time();
		//$return .= '&ts=' . time();
		
		
		$description = 'شماره فاکتور:'. $order->order_number;
		$currency = (!empty($order->currency)) ? $order->currency : $plgInfo->params->get('currency_code', $this->currency);;
		
		$amount = $order->grand_total;
		
		 
        require_once(JPATH_ROOT .'/plugins/djcatalog2payment/mellat/lib/nusoap.php');    

        $client = new nusoap_client('https://bpm.shaparak.ir/pgwchannel/services/pgw?wsdl');
        $namespace='http://interfaces.core.sw.bps.com/';



        $err = $client->getError();
        if ($err) {
            echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
            return;
        }     
        $parameters = array(
            'terminalId' => $terminalId,
            'userName' => $userName,
            'userPassword' => $userPassword,
            'orderId' => $order->id,
            'amount' => $amount,
            'localDate' => $localDate,
            'localTime' => $localTime,
            'additionalData' => $additionalData,
            'callBackUrl' => $notify_url,
            'payerId' => $payerId);

        $result = $client->call('bpPayRequest', $parameters, $namespace);
        $wsaddr = 'https://bpm.shaparak.ir/pgwchannel/startpay.mellat';    


        if ($client->fault) {
            echo '<h2>اشكال در پرداخت </h2><pre>';
            print_r($result);
            echo '</pre>';
            return;
        } 
        else {
            $err = $client->getError();
            if ($err) {
                echo '<h2>خطايي رخ داده </h2><pre>' . $err . '</pre>';
                return;
            } 
            else {
                $res = explode (',',$result);
                $ResCode = $res[0];

                if ($ResCode == "0") {
                
                  
                    ?>        
         
		<p style="text-align: center">در حال اتصال به درگاه بانک ... لطفا کمی صبر نمایید</p>


        <form name="paymentform" id="paymentform" method="post" action="<?php echo $wsaddr; ?>">
        <input type="hidden" name="TerminalId" value="<?php echo $terminalId; ?>">
        <input type="hidden" name="UserName" value="<?php echo $userName; ?>">
        <input type="hidden" name="UserPassword" value="<?php echo $userPassword; ?>">
        <input type="hidden" name="PayDate" id="PayDate" value="<?php echo $paydate; ?>">
        <input type="hidden" name="PayTime" id="PayTime" value="<?php echo $paytime; ?>">
        <input type="hidden" name="PayAmount" id="PayAmount" value="<?php echo $amount; ?>">
        <input type="hidden" name="PayOrderId" id="PayOrderId" value="<?php echo $order->id; ?>">
        <input type="hidden" name="PayAdditionalData" id="PayAdditionalData" value="<?php echo $additionalData; ?>">
        <input type="hidden" name="PayCallBackUrl" id="PayCallBackUrl" value="<?php echo $notify_url; ?>">
        <input type="hidden" name="PayPayerId" id="PayPayerId" value="<?php echo $payerId; ?>">
        <input type="hidden" name="RefId" id="RefId" value="<?php echo $res[1]; ?>">
         
        </form>        

        <br>
        <script type="text/javascript">document.getElementById('paymentform').submit();</script>
        

        
        <?php
        return;   
                } 
                else {
                echo '<h2>خطا در اتصال به درگاه بانك </h2><br> کد خطای ResCode:'.$ResCode;
                return;  
                }
            }
        }
 
		$app->close();
    }
    
	public function onDJC2PaymentDiscover($context, $plgInfo) {
		if ($context != 'com_djcatalog2.order.payment' || !$this->isAllowed($plgInfo)) {
			return;
		}
		
		$this->log('[onDJC2PaymentDiscover] '.$plgInfo->plugin);
		
		$app = JFactory::getApplication();
		$oid = $app->input->getInt('oid');
		if ($oid > 0) {
			
			$this->log('[onDJC2PaymentDiscover] order id: '.$oid);
			
			return $oid;
		}
	}
	
	public function onDJC2PaymentResponse($context, $order, $model, $plgInfo) {
		if ($context != 'com_djcatalog2.order.payment' || !$this->isAllowed($plgInfo)) {
			return;
		}
		
		$this->log('[onDJC2PaymentResponse] '.$plgInfo->plugin);
		
		$terminalId = $plgInfo->params->get('terminalid');
		$userName = $plgInfo->params->get('username');
		$userPassword = $plgInfo->params->get('userpassword');

		require_once(JPATH_ROOT .'/plugins/djcatalog2payment/mellat/lib/nusoap.php');    
		$refid = $_POST['RefId'];
        $rescode = $_POST['ResCode'];
        $verifySaleOrderId = $_POST['SaleOrderId']; 
        $verifySaleReferenceId = $_POST['SaleReferenceId'];    

		
		$app = JFactory::getApplication();
 

    
		if     ($rescode == '0' ){

			$err = $client->getError();
			if ($err) {
				$this->log('[onDJC2PaymentResponse] Constructor error'.$err);
				$app->close();
			}
	
			$parameters = array(
				'terminalId' => $terminalId,
				'userName' => $userName,
				'userPassword' => $userPassword,
				'orderId' => $verifySaleOrderId,
				'saleOrderId' => $verifySaleOrderId,
				'saleReferenceId' => $verifySaleReferenceId);
	
	
			$result = $client->call('bpVerifyRequest', $parameters, $namespace);
			$resultSettle = $client->call('bpSettleRequest', $parameters, $namespace);
	
			if ($result==415 or $result==51 or $result==55 or $result == 43  )
			{
				$this->log('[onDJC2PaymentResponse] verify error stp1');
				$app->close();
			}
			if (strlen($result)==0 or strlen($resultSettle)==0 or is_null($result) or is_null($resultSettle)  )
			{ 
				$this->log('[onDJC2PaymentResponse] verify error stp2');
				$app->close();
			} 
			
			
			
			if ($client->fault) {
				$this->log('[onDJC2PaymentResponse] fault');
				$app->close();
			} 
			else {
				foreach ($result as $arr){
					$resultStr = $arr;
				}
	
				$err = $client->getError();
				if ($err) {
					$this->log('[onDJC2PaymentResponse] fault'.$err);
					$app->close();
				} 
				else {
	
					if  ($resultStr ==0){
							if ($order->status == 'A' || $order->status == 'N') {
								
								$this->log('[onDJC2PaymentResponse] verifySaleReferenceId='.$verifySaleReferenceId.'verifySaleOrderId='.$verifySaleOrderId);
								
								$model->changeStatus($order, 'P', true, true, JText::_('پرداخت با موفقیت انجام گردید,شماره رسید پرداخت: '.$verifySaleReferenceId)); 
							}
					//$this->pm_mellatUpadteDatabasePre($jorderid,$verifySaleReferenceId,$verifySaleOrderId);
					}
	
				}
			}
			 
	}else{
	 $this->log('[onDJC2PaymentResponse] rescode error'.$rescode);
	 $app->close();
	}    

		$app->close();
	}

	private function log($msg) {
			
		if(!$this->debug) return;
		
		$fp = fopen(__DIR__.'/lib/logs.txt', 'a');
		fwrite($fp, print_r($msg, true));
		fwrite($fp, "\n");
		fclose($fp);
	}
}


