<?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_jegroupbuyAuthorizedotnet',JPATH_ROOT);

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

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

		$this->loadLanguage('plg_jegroupbuyAuthorizedotnet');
		$params["plugin_name"] = "jegroupbuyAuthorizedotnet";
		$params["icon"] = "";
		$params["logo"] = "authorized.jpg";
		$params["description"] = JText::_("PAYMENT_METHOD_DESC");
		$params["payment_method"] = JText::_("PAYMENT_METHOD_NAME");

		$params["login_id"] = $this->params->get("login_id");
		$params["transaction_key"] = $this->params->get("transaction_key");
		$params["currency_code"] = $this->params->get('currency_code', "USD");
		$params["account_type"] = $this->params->get('account_type', "test");
		$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 "notify" :
				$html = $this->_notify_url();
				break;
				case "paymentmessage" :
				$html = $this->_paymentsuccess();
				break;
				default :
				$html =  $this->process($tot);
				break;
			}
		}
		return $html;
	}
	function _notify_url()
	{
		$db = JFactory::getDBO();
		$app = JFactory::getApplication();
		$account_type=$this->params["account_type"];
		$Itemid = JRequest::getInt("Itemid",'0');
		$merchant_id = $this->params["login_id"];
		$merchant_key = $this->params["transaction_key"];
		$currency = $this->params["currency_code"];
		$user	= JFactory::getUser();
		$user_id	= JRequest::getInt('userid','0');
		//$id	= JRequest::getInt('id','0');

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

		$login_id = $this->params["login_id"];
		$transaction_key = $this->params["transaction_key"];
		$card_no = JRequest::getVar('card_no');
		if (isset($card_no))
		{
			//include_once "phpcreditcard.php";
			$card_num    = JRequest::getVar('card_no');
			$card_type   = JRequest::getVar('card_type');
			$exp_date    = JRequest::getVar('exp_date') . JRequest::getVar('exp_year');
			$amount      = $amount;
			$item_number   = $split_val[0];
			$description = "Product Sale"; //$_POST[''];

			$cvv		 = JRequest::getVar('card_code');
			if ( empty( $login_id ) || empty( $transaction_key ) )
			{
				return JError::raiseWarning( 'SOME_ERROR', JText::_( 'JE_NOTAUTHORISED' ) );
			}
			$post_url = "https://" . $account_type . ".authorize.net/gateway/transact.dll";

			$post_values = array(

			// the API Login ID and Transaction Key must be replaced with valid values
			"x_login"			=> $login_id,
			"x_tran_key"		=> $transaction_key,

			"x_version"			=> "3.1",
			"x_delim_data"		=> "TRUE",
			"x_delim_char"		=> "|",
			"x_relay_response"	=> "FALSE",
			"x_type"			=> "AUTH_CAPTURE",
			"x_method"			=> "CC",
			"x_card_num"		=> $card_num,
			"x_exp_date"		=> $exp_date,
			"x_card_code"       => $cvv,
			"x_amount"			=> $amount

			);

			if ( empty($post_values['x_card_num']) || empty($post_values['x_exp_date']) || empty($post_values['x_amount']) )
			{

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

			// This section takes the input fields and converts them to the proper format
			// for an http post.  For example: "x_login=username&x_tran_key=a1B2c3D4"
			$post_string = "";

			foreach( $post_values as $key => $value )
			{
				$post_string .= "$key=".urlencode($value)."&";
			}
			$post_string = rtrim( $post_string, "& " );

			$request = curl_init($post_url); // initiate curl object
			curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
			curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
			curl_setopt($request, CURLOPT_POSTFIELDS, $post_string); // use HTTP POST to send form data
			curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response.
			$post_response = curl_exec($request); // execute curl post and store results in $post_response

			curl_close ($request); // close curl object

			// This line takes the response and breaks it into an array using the specified delimiting character
			$response_array = explode($post_values["x_delim_char"],$post_response);


			if( $response_array[0] == 1 )
			{
				$ptype=JRequest::getVar('ptype');
				$txn_id = $post_values["x_card_num"];
				$pdate = gmdate("Y-m-d H:i:s");

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

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

				$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 = $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);
				unset ($_SESSION['cart'],$_SESSION['total']);
				//$app->redirect(JRoute::_('index.php?option=com_jegroupbuy&task=paymentReturnUrl&action=showresult&ptype='.$this->params["plugin_name"].'&Itemid='.$Itemid.'&ppc='.$ppcount.'&id='.$row->id));
				$app->redirect(JRoute::_(JURI::root().'index.php?option=com_jegroupbuy&view=jegroupbuy',false),JText::_("COM_JEGROUPBUY_PAYMENT_SUCCESS_MSG"));
			}
			else
			{
				$msg = $response_array[3] ;
				unset ($_SESSION['cart'],$_SESSION['total']);
				//$app->redirect(JRoute::_('index.php?option=com_jegroupbuy&task=paymentReturnUrl&action=showresult&ptype='.$this->params["plugin_name"].'&Itemid='.$Itemid.'&ppc='.$ppcount.'&id='.$row->id));
				$app->redirect(JRoute::_(JURI::root().'index.php?option=com_jegroupbuy&view=jegroupbuy',false),JText::_("COM_JEGROUPBUY_PAYMENT_FAILURE_MSG"));
			}
		}
	}

	function onPaymentMethodList($total_val)
	{

		$user	= JFactory::getUser();
		$Itemid = JRequest::getInt("Itemid",'0');

		$tot = base64_encode($total_val);

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

		$action_url = JRoute :: _('index.php?option=com_jegroupbuy&task=processPayment&ptype='.$this->params["plugin_name"].'&pactiontype=notify&userid='.$user->id.'&Itemid='.$Itemid.'&tot='.$tot,false);
		$ADN_form = "<script language='javascript'>function adotnetSubmitForm(){if(document.addtocart.card_no.value==''){alert('Credit Card Number Field is Empty!');return;}else if(document.addtocart.card_code.value==''){alert('Credit Card Security Code Field is Empty!');return;}else{document.addtocart.submit(); } }</script><form name='addtocart' action='".$action_url."' method='post'>
		<table align='left'>
		<tr><th colspan='3' style='text-align:left;'><b>Credit Cart Payment:</b></th></tr>
		<tr>
			<td width='40%'>Credit Card Type : </td><td>&nbsp;</td>
			<td width='20%'>
				<select name='card_type' id='card_type' style='width:202px;'>
				<option value='visa'>visa</option>
				<option value='Master_Card'>Master Card</option>
				<option value='American_Express'>American Express</option>
				</select>
			</td>
		</tr>
		<tr>
			<td>Credit Card Number : </td><td>&nbsp;</td>
			<td><input type='text' name='card_no' style='width:190px;'/></td>
		</tr>
		<tr>
		<td>Credit Card Security Code  : </td><td>&nbsp;</td>
		<td><input type='text' name='card_code' style='width:190px;'/></td>
		</tr>

		<tr>
		<td>Expiration Date : </td><td>&nbsp;</td>
		<td><select name='exp_date' id='exp_date' style='width:100px;'>
		                  <option value='1'>January</option>
						  <option value='02'>February</option>
						  <option value='03'>March</option>
						  <option value='04'>April</option>
						  <option value='05'>May</option>
						  <option value='06'>June</option>
						  <option value='07'>July</option>
		                  <option value='08'>August</option>
						  <option value='09'>September</option>
						  <option value='10'>October</option>
						  <option value='11'>November</option>
						  <option value='12'>December</option>


		                  </select>
						  <select name='exp_year' id='exp_year' style='width:100px;'>
		                  <option value='10'>2010</option>
						  <option value='11'>2011</option>
						  <option value='12'>2012</option>
						  <option value='13'>2013</option>
						  <option value='14'>2014</option>
						  <option value='15'>2015</option>
						  <option value='16'>2016</option>
		                  <option value='17'>2017</option>
						  <option value='18'>2018</option>
						  <option value='19'>2019</option>
						  <option value='20'>2020</option>

		                  </select></td>
						  </tr>
						  <tr><td></td><td>";

						$ADN_form .= "<input type='hidden' name='option' value='com_jegroupbuy' /><input type='hidden' name='task' value='processPayment' /><input type='hidden' name='ptype' value='".$this->params["plugin_name"]."' /><input type='hidden' name='pactiontype' value='notify' />";
						$ADN_form .= "</td></tr> </table>

		</form>";

		$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"]."<br/>".$ADN_form.'</p>
				</td>
				<td width="100" align="center">
					<a  style="text-decoration:none;" onclick="adotnetSubmitForm();" href="javascript:void(0);"><img border="0" src="'.JURI::root().'components/com_jegroupbuy/assets/images/buynow.png" width="89" height="28" ></a>
				</td>
			</tr>
		</table>';
		return $html;
	}

	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.quantity,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['quantity']=$rows->quantity;
		$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 onAfterSuccessfulPayment($inv_arg)
	{
		$db =& JFactory::getDBO();
		$sql = "SELECT number FROM #__ccinvoices_invoices WHERE id =".$inv_arg[0]." LIMIT 1";
		$db->setQuery($sql);
		$number = $db->loadResult();
		return sprintf(JText::_("AFTER_SUCCESSFULL_MSG"),$number);
	}
	function onAfterFailedPayment($val)
	{
		return JText::_("AFTER_FAILED_MSG");
	}
}

?>