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

class plgjegroupbuypaymentjegroupbuyCashondelivery extends JPlugin
{
	function plgjegroupbuypaymentjegroupbuyCashondelivery( &$subject, $config)
	{
		parent::__construct($subject, $config);
		$this->loadLanguage('plg_jegroupbuyCashondelivery');
		$params["plugin_name"] 		= "jegroupbuyCashondelivery";
		$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','');

		//$id = JRequest::getInt('id','');

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

		$tot = base64_decode($total);

		$post= JRequest::get('post');

		$html="";

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

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

	function process($post, $tot)
	{
		global $mainframe;

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

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

		$pdate 	= gmdate("Y-m-d");
		$txn_id = "TX".rand(1000, 9000).time();

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

			$query = 'SELECT title,deal_price,currencysymbol ' .
					'FROM #__jegroupbuy_product ' .
					'where id='.$id[$i];
			$db->setQuery( $query );
			$product_price[$i] = $db->loadObject();

			$query1 = 'INSERT INTO #__jegroupbuy_cashdelivery( pid, user_id, pro_price, pro_quantity, address, country, city, phone)' .
						' VALUES ( "'.$id[$i].'" ,"'.$user->id.'","'.$product_price[$i]->deal_price.'","'.$quan[$i].'" ,"'.$post['address'].'" ,"'.$post['country'].'","'.$post['city'].'","'.$post['phone'].'")'
						;
			$db->setQuery($query1);
			$db->query();

			$sql = 'INSERT INTO #__jegroupbuy_payment ( p_id,user_id,method , transaction_id , pdate, 	status, quantity)' .
						' VALUES ( "'.$id[$i].'" ,"'.$user->id.'","'.$post['ptype'].'","'.$txn_id.'" ,"'.$pdate.'" ,"0","'.$quan[$i].'")'
						;
			$db->setQuery($sql);
			$db->query();
		}

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

		$emailSubject	  = JText::_("ORDER_DETAILS_FROM")." - ". $data['sitename'];

		$emailBody = Coupontemp::couponTemplate($tot,$data['sitename'],$user->name,$data['fromname']);

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

		$url				= "index.php?option=com_jegroupbuy&task=paymentDetails&pid=".$id;

		return $mainframe->redirect($url, JText::_('ORDER_SUCCESSFULLY_SUBMITTED') );
	}

	function currency_symbols($sym)
	{
		if($sym == "1") $symbol = "&#36";
		elseif($sym == "2") $symbol = "&#163";
		elseif($sym == "3") $symbol = "&#165";
		elseif($sym == "4") $symbol = "&#128";
		elseif($sym == "5") $symbol = "&#8377";
		elseif($sym == "6") $symbol = "&#36";
		elseif($sym == "7") $symbol = "&#36";
		elseif($sym == "8") $symbol = "&#36";
		elseif($sym == "9") $symbol = "&#67&#72&#70";
		elseif($sym == "10") $symbol = "&#36";
		elseif($sym == "11") $symbol = "&#163";
		elseif($sym == "12") $symbol = "&#107&#114";
		elseif($sym == "13") $symbol = "&#107&#114";
		elseif($sym == "14") $symbol = "&#122&#322";
		elseif($sym == "15") $symbol = "&#107&#114";
		elseif($sym == "16") $symbol = "&#70&#116";
		elseif($sym == "17") $symbol = "&#75&#269";
		elseif($sym == "18") $symbol = "&#8362";
		elseif($sym == "19") $symbol = "&#36";
		elseif($sym == "20") $symbol = "&#82&#36";
		elseif($sym == "21") $symbol = "&#82&#77";
		elseif($sym == "22") $symbol = "&#8369";
		elseif($sym == "23") $symbol = "&#78&#84&#36";
		elseif($sym == "24") $symbol = "&#3647";
		else $symbol = "&#8356";

		return $symbol;
	}


	function onPaymentMethodList($value)
	{
		$val = base64_encode($value);
	?>
		<script type="text/javascript">

			function submitbutton(){
				var tables       = document.getElementsByTagName('input');
				var toggletables = [];
				for (i in tables) {
					if (tables[i].id) {
						var requ  = tables[i].className;
						var value = document.getElementById(tables[i].id).value;
						// Required Field...
						if(requ == 'required') {
							if (value == '' || value == null) {
								var inputerror 				= document.getElementById(tables[i].id);
								inputerror.style.border		= '1px solid red';
								isValid = false;
							} else {
								var inputerror 				= document.getElementById(tables[i].id);
								inputerror.style.border		= '1px solid #ABADB3';
								isValid = true;
							}
						}
					}
				}
				if(isValid == true)
				{
					document.cashdelivery.submit();
				} else{
					exit;
				}
			}

		</script>
	<?php


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

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

		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		$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);
		}
		$formcontent = "";

		$formcontent .='<form action="'.$form_action.'" name="cashdelivery" method="post">
					<table  style="font-weight:bold;" align="center" cellpadding="0" cellspacing="10" width="100%" border="0">' .
						'<tr> ' .
							'<td>'.
								'<table width="100%" border="0">' .
									'<tr>'.
										'<td>'.JText::_("JEGROUPBUY_COD_ADDRESS").' </td><td>&nbsp;</td><td><input class="required" type="text" name="address" id="address" value=""><span id="address-error"></span></td>' .
									'</tr>'.
									'<tr>'.
										'<td>'.JText::_("JEGROUPBUY_COD_COUNTRY").' </td><td>&nbsp;</td><td><input class="required" type="text" name="country" id="country" value=""><span id="country-error"></span></td>' .
									'</tr>'.
									'<tr>'.
										'<td>'.JText::_("JEGROUPBUY_COD_CITY").' </td><td>&nbsp;</td><td><input class="required" type="text" name="city" id="city" value=""><span id="city-error"></span></td>' .
									'</tr>'.
									'<tr>'.
										'<td>'.JText::_("JEGROUPBUY_COD_PHONE_NUMBER").' </td><td>&nbsp;</td><td><input class="required" type="text" name="phone" id="phone" value=""><span id="phone-error"></span></td>' .
									'</tr>'.
								'</table>'.
							'</td>'.
						'</tr>'.
						'<input type="hidden" name="ptype" value="'.$this->params["plugin_name"].'"/><input type="hidden" id="quantity_val" name="quantity_val" value="1"/></td>
					</table>
				</form>';

		$html ='<table cellpadding="5" cellspacing="0" width="100%" border="0">
				<tr>
				<td rowspan="2"><img style="margin-right:27px;margin-left:19px;" border="0" src="'.JURI::root().'components/com_jegroupbuy/assets/images/cashondelivery.png" width="125" height="49" ></td>' ;
		$html .='<td>
					<p style="text-align:justify;">'.$this->params["description"]."<br/>".$formcontent.'</p>
				</td>
				<td width="100" align="center">
					<a  style="text-decoration:none;" onclick="submitbutton();" 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;
	}
}
?>