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

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

class plgjegroupbuypaymentjegroupbuyPaypal extends JPlugin
{
	function plgjegroupbuypaymentjegroupbuyPaypal( &$subject, $config)
	{
		parent::__construct($subject, $config);
		$this->loadLanguage('plg_jegroupbuyPaypal');
		$params["plugin_name"] = "jegroupbuyPaypal";
		$params["icon"] = "paypal_icon.png";
		$params["logo"] = "paypal_overview.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["email_id"] = $this->params->get("email_id");
		$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($tot);
				break;
				case "paymentmessage" :
				$html = $this->_paymentsuccess();
				break;
				default :
				$html =  $this->process($tot);
				break;
			}
		}
		return $html;
	}
	
	function _notify_url($tot)
	{
		$db = JFactory::getDBO();

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

		$account_type=$this->params["testmode"];
		$user	= JFactory::getUser();
		$user_id	= JRequest::getInt('userid','0');
		$paypal_info = $_POST;
		$paypal_ipn = new paypal_ipn($paypal_info);
		foreach ($paypal_ipn->paypal_post_vars as $key=>$value)
		{
			if (getType($key)=="string")
			{
				eval("\$$key=\$value;");
			}
		}
		$paypal_ipn->send_response($account_type);
		
		if (!$paypal_ipn->is_verified())
		{
			die();
		}
		$paymentstatus=0;

		$res = $paypal_ipn->get_payment_status();

		switch($paypal_ipn->get_payment_status())
		{
			case 'Pending':
			$msg = "Pending Payment";
			break;

			case 'Completed':
			$msg = "Success";
			$sql = "SELECT username,email FROM #__users WHERE id=".$user_id;
			$db->setQuery($sql);
			$toemail = $db->loadObject();

			$pro_title = $paypal_ipn->paypal_post_vars['custom'];
			$custom_explode = explode(":",$pro_title);

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

			$txn_id = $paypal_ipn->paypal_post_vars['txn_id'];
			$ptype = JRequest::getVar('ptype');
			$pdate = gmdate("Y-m-d H:i:s");

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

			break;

			case 'Failed':
			$msg = "Failed Payment";
			break;

			case 'Denied':
			$msg = "Denied Payment";
			break;

			case 'Refunded':
			$msg = "Refunded Payment";
			break;

			case 'Canceled':
			$msg = "Cancelled reversal";
			break;

			default:
			$msg = "Unknown Payment Status";
			break;
		}
	}

	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 process($tot)
	{
		$db = JFactory::getDBO();
		$app = JFactory::getApplication();

		$split_val = explode(":",$tot);
		
		$id = explode(",",$split_val[0]);
		
		$tot_amount = $split_val[2];

		$deal_price = $split_val[2]/$split_val[1];

		$custom = $split_val[0].":".$split_val[1];

		$Itemid = JRequest::getInt("Itemid",'0');
		$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);
		}

		$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($id == "")
		{
			$link = JRoute::_('index.php?option=com_jegroupbuy&view=jegroupbuy');
			$app->redirect( $link);
		}

		$urlpaypal="";
		
		if ($this->params["testmode"]=="1")
		{
			$urlpaypal="https://www.sandbox.paypal.com/cgi-bin/webscr";
		}
		elseif ($this->params["testmode"]=="0")
		{
			$urlpaypal="https://www.paypal.com/cgi-bin/webscr";
		}
		$t_val = base64_encode($tot);

		$form ='<form id="paypalform" action="'.$urlpaypal.'" method="post">';
		$form .='<input type="hidden" name="cmd" value="_xclick">';
		$form .='<input type="hidden" id="custom" name="custom" value="'.$custom.'">';
		$form .='<input type="hidden" name="business" value="'.$this->params["email_id"].'">';
		$form .='<input type="hidden" name="currency_code" value="'.$this->params["currency_code"].'">';
		$form .='<input type="hidden" name="item_name" value="'.$itemname.'">';
		$form .='<input type="hidden" name="quantity" value="">';
		$form .='<input type="hidden" name="amount" value="'.$tot_amount.'">';
		$form .='<input type="hidden" name="cancel_return" value="'.JRoute::_(JURI::root().'index.php?option=com_jegroupbuy&task=paymentDetails&action=showresult&ptype='.$this->params["plugin_name"].'&Itemid='.$Itemid).'">';
		$form .='<input type="hidden" name="notify_url" value="'.JRoute::_(JURI::root().'index.php?option=com_jegroupbuy&task=processPayment&ptype='.$this->params["plugin_name"].'&pactiontype=notify&userid='.$user->id.'&tot='.$t_val.'&Itemid='.$Itemid).'">';
		//$form .='<input type="hidden" name="return" value="'.JRoute::_(JURI::root().'index.php?option=com_jegroupbuy&task=paymentReturnUrl&action=showresult&ptype='.$this->params["plugin_name"].'&Itemid='.$Itemid.'&ppc='.$ppcount.'&id='.$row->id).'">';
		$form .='<input type="hidden" name="return" value="'.JRoute::_(JURI::root().'index.php?option=com_jegroupbuy&task=paypalReturnUrl&action=showresult&ptype='.$this->params["plugin_name"].'&Itemid='.$Itemid).'">';
		$form .='</form>';
		echo $form;
		
	?>
		<script type="text/javascript">
			callpayment();
			function callpayment(){
				document.getElementById('paypalform').submit();
			}
		</script>
	<?php
	}

	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;
	}
}
class paypal_ipn
{
	var $paypal_post_vars;
	var $paypal_response;
	var $timeout;
	var $error_email;
	function paypal_ipn($paypal_post_vars) {
		$this->paypal_post_vars = $paypal_post_vars;
		$this->timeout = 120;
	}
	function send_response($account_type)
	{
		$fp  = '';
		if($account_type == '1')
		{
			$fp = @fsockopen( "www.sandbox.paypal.com", 80, $errno, $errstr, 120 );
		}else if($account_type == '0')
		{
			$fp = @fsockopen( "www.paypal.com", 80, $errno, $errstr, 120 );
		}
		if (!$fp) {
			$this->error_out("PHP fsockopen() error: " . $errstr , "");
		} else {
			foreach($this->paypal_post_vars AS $key => $value) {
				if (@get_magic_quotes_gpc()) {
					$value = stripslashes($value);
				}
				$values[] = "$key" . "=" . urlencode($value);
			}
			$response = @implode("&", $values);
			$response .= "&cmd=_notify-validate";
			fputs( $fp, "POST /cgi-bin/webscr HTTP/1.0\r\n" );
			fputs( $fp, "Content-type: application/x-www-form-urlencoded\r\n" );
			fputs( $fp, "Content-length: " . strlen($response) . "\r\n\n" );
			fputs( $fp, "$response\n\r" );
			fputs( $fp, "\r\n" );
			$this->send_time = time();
			$this->paypal_response = "";

			while (!feof($fp)) {
				$this->paypal_response .= fgets( $fp, 1024 );

				if ($this->send_time < time() - $this->timeout) {
					$this->error_out("Timed out waiting for a response from PayPal. ($this->timeout seconds)" , "");
				}
			}
			fclose( $fp );
		}
	}
	function is_verified() {
		//if( ereg("VERIFIED", $this->paypal_response) )
		if( $this->paypal_post_vars['payer_status'] == 'verified' )
			return true;
		else
			return false;
	}
	function get_payment_status() {
		return $this->paypal_post_vars['payment_status'];
	}
	function error_out($message)
	{

	}
}
?>