<?php
/**
 * JE GroupBuy package
 * @author J-Extension <contact@jextn.com>
 * @link http://www.jextn.com
 * @copyright (C) 2011 - 2012 J-Extension
 * @license GNU/GPL, see LICENSE.php for full license.
**/
/** ensure this file is being included by a parent file */
defined('_JEXEC') or die('Restricted access');
/** Import library dependencies */

jimport('joomla.event.plugin');

$lang = JFactory::getLanguage();
$lang->load('plg_jegroupbuyBanktransfer',JPATH_ROOT);

require_once( JPATH_COMPONENT . DS . 'helpers' . DS . 'functions.inc.php' );

class plgjegroupbuypaymentjegroupbuyBanktransfer extends JPlugin
{
	function plgjegroupbuypaymentjegroupbuyBanktransfer( &$subject, $config)
	{
		parent::__construct($subject, $config);
		$this->loadLanguage('plg_jegroupbuyBanktransfer');
		$params["plugin_name"] 		= "jegroupbuyBanktransfer";
		$params["icon"] 			= "bankwire.png";
		$params["logo"] 			= "bankwire.png";
		$params["description"] 		= JText::_("BANK_PAYMENT_METHOD_DESC");
		$params["payment_method"] 	= JText::_("PAYMENT_METHOD_NAME");
		$params["bank_name"] 		= $this->params->get("bank_name");
		$params["acc_no"] 			= $this->params->get("acc_no");
		$params["acc_name"] 		= $this->params->get("acc_name");
		$params["branch_name"] 		= $this->params->get("branch_name");
		$this->params 				= $params;

	}

	function onProcessPayment()
	{
		$ptype = JRequest::getVar('ptype','');

		$total = JRequest::getVar('tot');
		$tot = base64_decode($total);

		$html="";

		if($ptype == $this->params["plugin_name"])
		{
			$action = JRequest::getVar('pactiontype','');

			switch ($action)
			{
				case "process" :
				$html = $this->process($tot);
				break;
				case "paymentmessage" :
				$html = $this->_paymentsuccess($tot);
				break;
				default :
				$html =  $this->process($tot);
				break;
			}
		}
		return $html;
	}


	function process($tot)
	{
		global $mainframe;
		$db 		= &JFactory::getDBO();
		$app 		= JFactory::getApplication();
		$Itemid 	= JRequest::getInt("Itemid",'0');
		$user		= &JFactory::getUser();
		$mainframe	= &JFactory::getApplication();

		//$total = JRequest::getVar('tot');
		//$tot = base64_decode($total);

		$split_val = explode(":",$tot);

		$id = explode(",",$split_val[0]);

		$tot_amount = $split_val[2];

		if ( $user->get('guest')) {
			$url = base64_encode(JRoute::_('index.php?option=com_jegroupbuy&view=jegroupbuy'));
			$link = "index.php?option=com_users&view=login&return=".$url;
			$app->redirect( $link);
		}

		$ptitle = "";

		for($j=0;$j<count($id); $j++)
		{
			$query	= "SELECT title FROM #__jegroupbuy_product WHERE id=".$id[$j];
			$db->setQuery($query);
			$prod_title[$j] = $db->loadResult();

			if($ptitle == "" || $ptitle == null)
				$ptitle = $prod_title[$j];
			else
				$ptitle .= ",".$prod_title[$j];
		}

		//$itemname = $row->title;
		$itemname = $ptitle;

		$amount = $tot_amount;

		for($i=0;$i<count($id); $i++)
		{
			$sql		 = "SELECT sum(quantity) FROM #__jegroupbuy_payment WHERE p_id=".$id[$i]." AND user_id = ".$user->id;
			$db->setQuery($sql);
			$ppcount[$i] = $db->loadResult();
		}

		//if($row->id == "")
		if($id == "")
		{
			$link = JRoute::_('index.php?option=com_jegroupbuy&view=jegroupbuy');
			$app->redirect( $link);
		}

		$ptype=JRequest::getVar('ptype');
		$pdate = gmdate("Y-m-d H:i:s");
		$text_time = substr(time(),-6);
		$txn_id = rand(1000, 9000).$text_time;


		$sql = "SELECT username,email FROM #__users WHERE id=".$user->id;
		$db->setQuery($sql);
		$toemail = $db->loadObject();

		$config	= JFactory::getConfig();
		$data['fromname'] = $mainframe->getCfg('fromname');
		$data['mailfrom'] = $mainframe->getCfg('mailfrom');
		$data['sitename'] = $mainframe->getCfg('sitename');
		$data['siteurl']  = JUri::base();
		$data['email']    = $toemail->email;

		//User Subject
		$emailSubject	  = sprintf (JText::_("YOUR_ORDER_DETAILS_FROM"),$txn_id,$pdate);

		//Admin Subject
		$emailSubject1	  = sprintf (JText::_("ORDER_DETAILS_FROM"),$txn_id,$pdate);

		$quan = explode(",",$split_val[1]);

		for($i=0;$i<count($id); $i++)
		{
			$query		= $db->getQuery(true);
			$query		 = "SELECT sum(quantity) FROM #__jegroupbuy_payment WHERE p_id=".$id[$i]." AND user_id = ".$user->id;
			$db->setQuery((string)$query);
			$ppcount[$i] = $db->loadResult();

			$j = $quan[$i];

			$querys 	= $db->getQuery(true);
			$querys 	= 'INSERT INTO #__jegroupbuy_payment ( p_id,user_id,method , transaction_id , pdate, status,quantity)' .
					' VALUES ( "'.$id[$i].'" ,"'.$user->id.'","'.$ptype.'","'.$txn_id.'" ,"'.$pdate.'" ,"1","'.$j.'" )'
					;
			$db->setQuery((string)$querys);
			$db->execute();
		}

		$emailBody 	= sprintf (JText::_( 'CONTENT_USER_BOUGHT_NEW' ),ucfirst($toemail->username),$txn_id,$itemname,$product_price->currencysymbol,$amount,$split_val[1],$pdate,$this->params['bank_name'],$this->params['branch_name'],$this->params['acc_name'],$this->params['acc_no']);
		$emailBody1 = html_entity_decode($emailBody, ENT_QUOTES);

		//User mail
		$mailcontent = '<span style="font-size:16px;font-family:Arial;">'.$emailBody1.'</span>';

		JFactory::getMailer()->sendMail( $data['mailfrom'], $data['fromname'], $data['email'], $emailSubject, $mailcontent, 1 );

		$emailBody2 = sprintf ( JText::_( 'CONTENT_USER_BOUGHT_ADMIN_NEW' ),ucfirst($data['fromname']),$txn_id,$itemname,$product_price->currencysymbol,$amount,$split_val[1],$pdate,$this->params['bank_name'],$this->params['branch_name'],$this->params['acc_name'],$this->params['acc_no']);
		$emailBody3 = html_entity_decode($emailBody2, ENT_QUOTES);

		//Admin mail
		$mailcontent1 = '<span style="font-size:16px;font-family:Arial;">'.$emailBody3.'</span>';


		JFactory::getMailer()->sendMail( $data['email'], $toemail->username, $data['mailfrom'], $emailSubject1, $mailcontent1, 1 );

		$url				= "index.php?option=com_jegroupbuy&task=paymentReturnBank&pid=".$id;
		return $mainframe->redirect($url, JText::_('ORDER_SUCCESSFULLY_SUBMITTED') );

	}

	function onPaymentMethodList($val)
	{

		//$bus_id= $this->params["email_id"];

		$tot = base64_encode($val);

		$paymentLogoPath = JURI::root()."plugins/jegroupbuypayment/".$this->params["plugin_name"]."/".$this->params["plugin_name"]."/images/".$this->params["logo"];

		$form_action = JRoute::_("index.php?option=com_jegroupbuy&task=processPayment&ptype=".$this->params["plugin_name"]."&pactiontype=process&tot=".$tot, false);

		$html ='<table cellpadding="5" cellspacing="0" width="100%" border="0">
			<tr>';
				if($this->params["logo"] != ""){
			$html .='<td width="160" align="center">
					<img src="'.$paymentLogoPath.'" title="'. $this->params["payment_method"].'"/>
				</td>';
				 }
				$html .='<td>
					<p style="text-align:justify;">'.$this->params["description"].'</p>
				</td>
				<td width="100" align="center">
					<a  style="text-decoration:none;" href="'.$form_action.'"><img border="0" src="'.JURI::root().'components/com_jegroupbuy/assets/images/buynow.png" width="89" height="28" ></a>
				</td>
			</tr>
		</table>';
		return $html;
	}
}
?>
