<?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_jegroupbuypayment_jegroupbuyPaypal',JPATH_ROOT);
$lang->load('plg_jegroupbuyGooglecheckout',JPATH_ROOT);
//exit;

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

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

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

		$params["merchant_id"] = $this->params->get("merchant_id");
		$params["merchant_key"] = $this->params->get("merchant_key");
		$params["account_type"] = $this->params->get('account_type', "sandbox");
		$params["currency_code"] = $this->params->get('currency_code', "USD");

		$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();
		$merchant_id = $this->params["merchant_id"];
		$merchant_key = $this->params["merchant_key"];
		$server_type = $this->params["account_type"];
		$currency = $this->params["currency_code"];
		$user	= JFactory::getUser();
		$user_id	= JRequest::getInt('userid','0');

		require_once(JPATH_BASE.DS."plugins".DS."jegroupbuypayment".DS."jegroupbuyGooglecheckout".DS."jegroupbuyGooglecheckout".DS."googleresponse.php");
		require_once(JPATH_BASE.DS."plugins".DS."jegroupbuypayment".DS."jegroupbuyGooglecheckout".DS."jegroupbuyGooglecheckout".DS."googlemerchantcalculations.php");
		require_once(JPATH_BASE.DS."plugins".DS."jegroupbuypayment".DS."jegroupbuyGooglecheckout".DS."jegroupbuyGooglecheckout".DS."googleresult.php");
		require_once(JPATH_BASE.DS."plugins".DS."jegroupbuypayment".DS."jegroupbuyGooglecheckout".DS."jegroupbuyGooglecheckout".DS."googlerequest.php");

		$Gresponse = new GoogleResponse($merchant_id, $merchant_key);
		$path 			= JPATH_BASE.DS."plugins".DS."jegroupbuypayment".DS."jegroupbuyGooglecheckout".DS."jegroupbuyGooglecheckout".DS."error_log".DS;
		$Gresponse->SetLogFiles($path . 'googleerror.log', $path . 'googlemessage.log', L_ALL);

		$Grequest = new GoogleRequest($merchant_id, $merchant_key, $server_type, $currency);
		//Setup the log file
		$Gresponse->SetLogFiles(RESPONSE_HANDLER_ERROR_LOG_FILE,RESPONSE_HANDLER_LOG_FILE, L_ALL);
		// Retrieve the XML sent in the HTTP POST request to the ResponseHandler

		$xml_response = isset($HTTP_RAW_POST_DATA)? $HTTP_RAW_POST_DATA:file_get_contents("php://input");

		if (get_magic_quotes_gpc())
		{
			$xml_response = stripslashes($xml_response);
		}

		list($root, $data) = $Gresponse->GetParsedXML($xml_response);
		$Gresponse->SetMerchantAuthentication($merchant_id, $merchant_key);

		switch ($root)
		{
		case "request-received":
		{
			break;
		}
		case "error":
		{
			break;
		}
		case "diagnosis":
		{
			break;
		}
		case "checkout-redirect":
		{
			break;
		}
		case "merchant-calculation-callback":
		{
			// Create the results and send it
			$merchant_calc = new GoogleMerchantCalculations($currency);
			// Loop through the list of address ids from the callback
			$addresses = get_arr_result($data[$root]['calculate']['addresses']['anonymous-address']);
			foreach($addresses as $curr_address)
			{
				$curr_id = $curr_address['id'];
				$country = $curr_address['country-code']['VALUE'];
				$city = $curr_address['city']['VALUE'];
				$region = $curr_address['region']['VALUE'];
				$postal_code = $curr_address['postal-code']['VALUE'];

				// Loop through each shipping method if merchant-calculated shipping
				// support is to be provided
				if(isset($data[$root]['calculate']['shipping']))
				{
					$shipping = get_arr_result($data[$root]['calculate']['shipping']['method']);
					foreach($shipping as $curr_ship)
					{
						$name = $curr_ship['name'];
						//Compute the price for this shipping method and address id
						$price = 12; // Modify this to get the actual price
						$shippable = "true"; // Modify this as required
						$merchant_result = new GoogleResult($curr_id);
						$merchant_result->SetShippingDetails($name, $price, $shippable);

						if($data[$root]['calculate']['tax']['VALUE'] == "true") {
						//Compute tax for this address id and shipping type
						$amount = 15; // Modify this to the actual tax value
						$merchant_result->SetTaxDetails($amount);
						}
						if(isset($data[$root]['calculate']['merchant-code-strings']['merchant-code-string']))
						{
							$codes = get_arr_result($data[$root]['calculate']['merchant-code-strings']['merchant-code-string']);
							foreach($codes as $curr_code)
							{
								//Update this data as required to set whether the coupon is valid, the code and the amount
								$coupons = new GoogleGiftcerts("true", $curr_code['code'], 10, "debugtest");
								$merchant_result->AddGiftCertificates($coupons);
							}
						}
						$merchant_calc->AddResult($merchant_result);
					}
				} else
				{
					$merchant_result = new GoogleResult($curr_id);
					if($data[$root]['calculate']['tax']['VALUE'] == "true")
					{
						//Compute tax for this address id and shipping type
						$amount = 15; // Modify this to the actual tax value
						$merchant_result->SetTaxDetails($amount);
					}
					$codes = get_arr_result($data[$root]['calculate']['merchant-code-strings']
					['merchant-code-string']);
					foreach($codes as $curr_code)
					{
						//Update this data as required to set whether the coupon is valid, the code and the amount
						$coupons = new GoogleGiftcerts("true", $curr_code['code'], 10, "debugtest");
						$merchant_result->AddGiftCertificates($coupons);
					}
					$merchant_calc->AddResult($merchant_result);
				}
			}
			$Gresponse->ProcessMerchantCalculations($merchant_calc);
			break;
		}
		case "new-order-notification":
		{
			$data	= $data[$root];
			$item	= isset( $data['shopping-cart']['items']['item'][0]) ? $data['shopping-cart']['items']['item'][0] : @$data['shopping-cart']['items']['item'];
			$item_number	= @$item['merchant-private-item-data']['item_number']['VALUE'];

			$id = $item_number;
			$txn_id =  @$data['google-order-number']['VALUE'];

			$id				= @$item['merchant-private-item-data']['item_number']['VALUE'];
			$user_id		= @$item['merchant-private-item-data']['userid']['VALUE'];

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

			$already					= $this->alreadyExists( $txn_id );

			if($already == false && $user_id != 0 && $id != 0) {

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

				$split_val = explode(":",$tot);
				$id = explode(",",$split_val[0]);
				$quan = explode(",",$split_val[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;
				$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);

			}
			$Gresponse->SendAck();
			break;
		}
		case "order-state-change-notification":
		{
			$Gresponse->SendAck();
			$new_financial_state = $data[$root]['new-financial-order-state']['VALUE'];
			$new_fulfillment_order = $data[$root]['new-fulfillment-order-state']['VALUE'];
			switch($new_financial_state)
			{
				case 'REVIEWING':
				{
					break;
				}
				case 'CHARGEABLE':
				{
					break;
				}
				case 'CHARGING':
				{
					break;
				}
				case 'CHARGED':
				{
					break;
				}
				case 'PAYMENT_DECLINED':
				{
					break;
				}
				case 'CANCELLED':
				{
					break;
				}
				case 'CANCELLED_BY_GOOGLE':
				{
					break;
				}
				default:
				break;
			}
			switch($new_fulfillment_order)
			{
				case 'NEW':
				{
					break;
				}
				case 'PROCESSING':
				{
					break;
				}
				case 'DELIVERED':
				{
					break;
				}
				case 'WILL_NOT_DELIVER':
				{
					break;
				}
				default:
					break;
			}
			break;
		}

		case "charge-amount-notification":
		{
			$Gresponse->SendAck();
			break;
		}
		case "chargeback-amount-notification":
		{
			$Gresponse->SendAck();
			break;
		}
		case "refund-amount-notification":
		{
			$Gresponse->SendAck();
			break;
		}
		case "risk-information-notification":
		{
			$Gresponse->SendAck();
			break;
		}
		default:
			$Gresponse->SendBadRequestStatus("Invalid or not supported Message");
			break;
		}

	}

	function process($tot)
	{
		echo "process welcome";

		$db = &JFactory::getDBO();

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

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

		$tot_amount = $split_val[2];

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

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

		$amount = $split_val[2];

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


		$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;
			$this->setRedirect( $link);
		}

		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');
			$this->setRedirect( $link);
		}

		require_once(JPATH_BASE.DS."plugins".DS."jegroupbuypayment".DS."jegroupbuyGooglecheckout".DS."jegroupbuyGooglecheckout".DS.'googlecart.php');
		require_once(JPATH_BASE.DS."plugins".DS."jegroupbuypayment".DS."jegroupbuyGooglecheckout".DS."jegroupbuyGooglecheckout".DS.'googleitem.php');
		require_once(JPATH_BASE.DS."plugins".DS."jegroupbuypayment".DS."jegroupbuyGooglecheckout".DS."jegroupbuyGooglecheckout".DS.'googlesubscription.php');

		$merchant_id = $this->params["merchant_id"];  // Your Merchant ID
		$merchant_key = $this->params["merchant_key"];  // Your Merchant Key
		$server_type = $this->params["account_type"];  // or production
		$currency = $this->params["currency_code"];

		// if recurring not enabled & life time subscriptions,

			$cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $currency );
 			$subscription_item	= new GoogleSubscription( "google", "DAILY", $amount);
			$recurrent_item 	= new GoogleItem( $itemname, $itemname, 1, $amount );

		//------------

		$recurrent_item->SetMerchantPrivateItemData(
			new MerchantPrivateItemData(
				array(
						'item_number' => $split_val[0],
						'userid' => $user->id,
					 )
				)
			);

		$link	=  JURI::root().'index.php?option=com_jegroupbuy&view=jegroupbuy';
		$recurrent_item->SetURLDigitalContent($link, '', 'godwins');

		//------------

		$subscription_item->SetItem($recurrent_item);
		$recurrent_item->SetSubscription($subscription_item);
		$cart->AddItem($recurrent_item);

		echo $cart->CheckoutButtonCode("MEDIUM");



	}
	function onPaymentMethodList($total_val)
	{
		$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"];
		$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;
	}

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

	function alreadyExists( $txn_id )
	{
		$where	= array();
		// Joomla builtin functions
			$db 	 = & JFactory::getDBO();

		$where[]	 = $db->nameQuote( 'transaction_id' ) . ' = ' . $db->Quote( $txn_id );

		$where		 = count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '';

		$query 		 = 'SELECT count(*) FROM ' . $db->nameQuote( '#__jegroupbuy_payment' ) .
				  		$where;

		$db->setQuery( $query );

		if (!$db->query())	{
			echo $db->getErrorMsg();
		}

		$already 	 = $db->loadResult();

		if ( $already > 0 )
			return true;
		else
			return false;

	}
}

?>