<?php
/** 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_jegroupbuyccAvenue',JPATH_ROOT);

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

class plgjegroupbuypaymentjegroupbuyccAvenue extends JPlugin
{
	function plgjegroupbuypaymentjegroupbuyccAvenue( &$subject, $config)
	{
		parent::__construct($subject, $config);

		$this->loadLanguage('plg_jegroupbuyccAvenue');
		$params["plugin_name"] = "jegroupbuyccAvenue";
		$params["icon"] = "";
		$params["logo"] = "ccavenue.png";
		$params["description"] = JText::_("PAYMENT_METHOD_DESC");
		$params["payment_method"] = JText::_("PAYMENT_METHOD_NAME");
		//$params["testmode"] = $this->params->get("test");
		$params["currency_code"] = $this->params->get("currency_code");
		$params["merchant_id"] = $this->params->get("merchant_id");
		$params["working_key"] = $this->params->get("working_key");

		$this->params = $params;

	}
	function onProcessPayment()
	{
		$ptype = JRequest::getVar('ptype','');
		//$id = JRequest::getInt('id','');

		$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 "notify" :
				$html = $this->_notify_url($tot);
				break;
				case "paymentmessage" :
				$html = $this->_paymentsuccess();
				break;
				default :
				$html =  $this->process($tot);
				break;
			}
		}
		return $html;
	}
	function _notify_url($tot)
	{
		$db = JFactory::getDBO();
		$user	= JFactory::getUser();
		$app = JFactory::getApplication();
		$user_id	= JRequest::getInt('userid','0');
		$Itemid = JRequest::getInt("Itemid",'0');

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

		require_once(JPATH_BASE.DS."plugins".DS."jegroupbuypayment".DS."jegroupbuyccAvenue".DS."jegroupbuyccAvenue".DS."libfuncs.php");

		$WorkingKey			= $this->params["working_key"]; //put in the 32 bit working key in the quotes provided here
		$Merchant_Id		= $_REQUEST['Merchant_Id'];
		$Amount				= $_REQUEST['Amount'];
		$Order_Id			= $_REQUEST['Order_Id'];
		$Merchant_Param		= $_REQUEST['Merchant_Param'];
		$Checksum			= $_REQUEST['Checksum'];
		$AuthDesc			= $_REQUEST['AuthDesc'];

		$Checksum			= verifyChecksum($Merchant_Id, $Order_Id , $Amount, $AuthDesc, $Checksum, $WorkingKey);


		$mc_gross			= $_REQUEST['Amount'];
		$mc_currency		= $this->params["currency_code"];
		$payer_id			= $_REQUEST['Order_Id'];
		$txn_id				= $_REQUEST['Merchant_Id'];
		$payment_type		= $this->params["plugin_name"];
		$payment_status		= 'Completed';
		$payer_email		= $_REQUEST['billing_cust_email'];
		$date				= date('Y-m-d');
		$residence_country	= $_REQUEST['billing_cust_country'];

		$explode_mparam = explode(":",$Merchant_Param);

		$id = explode(",",$explode_mparam[0]);
		$quan= explode(",",$explode_mparam[1]);

		//$id = $Merchant_Param;
		/*$sql ="SELECT * FROM #__jegroupbuy_product WHERE id=".$id." AND expired <> 1 LIMIT 1";
		$db->setQuery($sql);
		$row = $db->loadObject();

		$sql ="SELECT count(*) FROM #__jegroupbuy_payment WHERE p_id=".$id." AND user_id = ".$user->id;
		$db->setQuery($sql);
		$ppcount = $db->loadResult();*/

		for($j=0;$j<count($id); $j++)
		{

			$sql ="SELECT * FROM #__jegroupbuy_product WHERE id=".$id[$j]." AND expired <> 1";
			$db->setQuery($sql);
			$row[$j] = $db->loadObject();

			$sql1 ="SELECT count(*) FROM #__jegroupbuy_payment WHERE p_id=".$id[$j]." AND user_id = ".$user->id;
			$db->setQuery($sql1);
			$ppcount[$j] = $db->loadResult();
		}

		$ptype=JRequest::getVar('ptype');
		$pdate = gmdate("Y-m-d H:i:s");

		if($Checksum=="true" && $AuthDesc=="Y") {
			//----------------------------------------------------------------------------------------
			$sql = "SELECT username,email FROM #__users WHERE id=".$user_id;
			$db->setQuery($sql);
			$toemail = $db->loadObject();

			$config	= JFactory::getConfig();
			$data['fromname'] = $config->get('fromname');
			$data['mailfrom'] = $config->get('mailfrom');
			$data['sitename'] = $config->get('sitename');
			$data['siteurl']  = JUri::base();
			$data['email']    = $toemail->email;
			$emailSubject	  =  JText::_("PRODUCT_COUPON_FROM").$data['sitename'];

			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 = (int)$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 = Coupontemp::couponTemplate($tot,$data['sitename'],$toemail->username,$data['fromname']);

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

			$app->setRedirect(JRoute::_('index.php?option=com_jegroupbuy&view=jegroupbuy',false),JText::_("COM_JEGROUPBUY_PAYMENT_SUCCESS_MSG"));

			//$app->redirect(JRoute::_('index.php?option=com_jegroupbuy&task=paymentReturnUrl&action=showresult&ptype='.$this->params["plugin_name"].'&Itemid='.$Itemid.'&ppc='.$ppcount.'&id='.$row->id));
		} else if($Checksum=="true" && $AuthDesc=="B") {
			//----------------------------------------------------------------------------------------
			$sql = "SELECT username,email FROM #__users WHERE id=".$user_id;
			$db->setQuery($sql);
			$toemail = $db->loadObject();

			$config	= JFactory::getConfig();
			$data['fromname'] = $config->get('fromname');
			$data['mailfrom'] = $config->get('mailfrom');
			$data['sitename'] = $config->get('sitename');
			$data['siteurl']  = JUri::base();
			$data['email']    = $toemail->email;
			$emailSubject	  =  JText::_("PRODUCT_COUPON_FROM").$data['sitename'];

			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 = (int)$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 = Coupontemp::couponTemplate($tot,$data['sitename'],$toemail->username,$data['fromname']);

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

			$app->setRedirect(JRoute::_('index.php?option=com_jegroupbuy&view=jegroupbuy',false),JText::_("COM_JEGROUPBUY_PAYMENT_SUCCESS_MSG"));
		} else if($Checksum=="true" && $AuthDesc=="N") {

			$app->setRedirect(JRoute::_('index.php?option=com_jegroupbuy&view=jegroupbuy',false),JText::_("COM_JEGROUPBUY_PAYMENT_FAILURE_MSG"));
		} else {

			$app->setRedirect(JRoute::_('index.php?option=com_jegroupbuy&view=jegroupbuy',false),JText::_("COM_JEGROUPBUY_PAYMENT_FAILURE_MSG"));
		}


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

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

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

		$amount = $split_val[2];


		$user	=& JFactory::getUser();
		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);
		}

		/*$sql ="SELECT * FROM #__jegroupbuy_product WHERE id=".$id." AND expired <> 1 LIMIT 1";
		$db->setQuery($sql);
		$row = $db->loadObject();

		$amount = $row->deal_price;
		$itemname = $row->title;

		$sql ="SELECT count(*) FROM #__jegroupbuy_payment WHERE p_id=".$id." AND user_id = ".$user->id;
		$db->setQuery($sql);
		$ppcount = $db->loadResult();
*/

		$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 = $ptitle;

		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);
		}

		require_once(JPATH_BASE.DS."plugins".DS."jegroupbuypayment".DS."jegroupbuyccAvenue".DS."jegroupbuyccAvenue".DS."libfuncs.php");

		$Merchant_Id = $this->params["merchant_id"];
		$Amount				= $amount ;
		$Order_Id				= "PRO-".time();
		$Redirect_Url			= JURI::root().'index.php?option=com_jegroupbuy&task=paymentReturnUrl&action=showresult&ptype='.$this->params["plugin_name"].'&Itemid='.$Itemid.'&ppc='.$ppcount.'&id='.$row->id;
		$WorkingKey				= $this->params["working_key"];
		$Checksum				= getCheckSum($Merchant_Id,$Amount,$Order_Id ,$Redirect_Url,$WorkingKey);

		//$Merchant_Param			= $row->id;
		$payid		= 'https://www.ccavenue.com/shopzone/cc_details.jsp';

		$form ='<form method="post" action="'.$payid.'" name="ccavenueform" id="ccavenueform">';
		$form .='<input type="hidden" name="Merchant_Id" value="'. $Merchant_Id.'">';
		$form .='<input type="hidden" name="Amount" value="'.$Amount.'">';
		$form .='<input type="hidden" name="Order_Id" value="'. $Order_Id.'">';
		$form .='<input type="hidden" name="Redirect_Url" value="'. $Redirect_Url.'">';
		$form .='<input type="hidden" name="billing_cust_notes" value="SUB-MERCHANT TEST">';
		$form .='<input type="hidden" name="Checksum" value="'. $Checksum.'">';
		$form .='<input type="hidden" name="Merchant_Param" value="'. $tot.'">';
		$form .='</form>';

		echo $form;
	?>
		<script type="text/javascript">
		 	document.getElementById('ccavenueform').submit()
		</script>
	<?php
	}

	function getCouponTemplate($pid)
	{
		$db = JFactory::getDBO();
		$user	=& JFactory::getUser();

		$sql = "SELECT pro.*,u.email as user_email,u.username,s.address,s.contact_number,py.transaction_id,py.method,s.store_logo,s.email,s.shop_url,py.id,py.pdate,py.status FROM #__jegroupbuy_product AS pro"
			   ." LEFT JOIN #__jegroupbuy_stores AS s ON s.id = pro.store_id"
			   ." LEFT JOIN #__jegroupbuy_payment AS py ON py.p_id = pro.id"
			   ." LEFT JOIN #__users AS u ON u.id = py.user_id"
			   ." WHERE py.id=".$pid;
		$db->setQuery( $sql );
		$rows = $db->loadObject();

		$query = 'SELECT template FROM #__jegroupbuy_template where id=1';
		$db->setQuery( $query );
		$template = $db->loadResult();

		//store fields
		$op_val['shop_address_1']=$rows->address;
		$op_val['shop_phone']=$rows->contact_number;
		$op_val['shop_email']=$rows->email;
		$op_val['shop_url']=$rows->shop_url;
		if($rows->store_logo!="")
		{
			$op_val['logo']='<img width="25%" src="'.JURI::root().'images/jegroupbuy/storelogo/'.$rows->store_logo.'"/>';
		}
		else
		{
			$op_val['logo']="";
		}


		//product fields
		$op_val['coupon_code']=$rows->coupon_code;
		$op_val['coupon_date']=$rows->deal_to_date;

		//payment field
		$op_val['order_number']=$rows->id;
		$op_val['order_date']=JHTML::_('date',$rows->pdate, JText::_('DATE_FORMAT_LC4').' H:i');
		if($rows->status =="1")
			$op_val['order_status']=JText::_('CC_PAYMENT_SUCCESS_MSG_TEMPLATE');
		else
			$op_val['order_status']=JText::_('CC_PAYMENT_UNSUCCESS_MSG_TEMPLATE');
		$op_val['transaction_id']=$rows->transaction_id;

		//product fields
		$price=substr($rows->product_price,1);
		$op_val['product_name']=$rows->title;
		$op_val['product_price']=$rows->product_price;
		$op_val['discount_price']=$rows->product_discount;
		$op_val['you_save']=$rows->you_save;
		$op_val['deal_price']=$rows->deal_price;

		$op_val['user_name']		= $rows->username;
		$op_val['user_mailid']		= $rows->user_email;
		$op_val['user_payment']		= $rows->method;

		foreach($op_val as $op_vals=>$value)
		{
			if(trim($value)=="")
			{
				$find = "{".$op_vals."}";
				$template=str_replace($find,"",$template);
			}
			else
			{
				$find = "{".$op_vals."}";
				$template=str_replace($find,$value,$template);
			}
		}
		return $template;
	}

	function onPaymentMethodList($total_val)
	{
		$tot = base64_encode($total_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;
	}
}
?>