<?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.
**/

// Check to ensure this file is included in Joomla!
	defined('_JEXEC') or die('Restricted access');


// Import Joomla predefined functions
	jimport( 'joomla.application.component.view' );

class jegroupbuyViewpaymentdetails  extends JView
{

	function display( $tpl = null )
	{
		$app		= JFactory::getApplication();
		$params 	= $app->getParams();
		$user		= & JFactory::getUser();
		$db			= JFactory::getDBO();
		$id 		= JRequest::getInt("pid","");
		$result 	= JRequest::getVar("result","");
		$pay 		= JRequest::getVar("pay","");
		$action		= JRequest::getVar('action','');
		$ptype		= JRequest::getVar('ptype','');

		$controller			= JController::getInstance('paymentdetails');

		if($this->_layout != 'process')
		{
			if ( $user->get('guest'))
			{
				if($id > 0)
				{
					$url = base64_encode(JRoute::_('index.php?option=com_jegroupbuy&task=paymentDetails&pid='.$id, false));
				}else
				{
					$url = base64_encode(JRoute::_('index.php?option=com_jegroupbuy&view=jegroupbuy', false));
				}
				$link = JRoute::_('index.php?option=com_users&view=login&return='.$url, false);
				$app->Redirect($link);
			} else {
				$cart = $_SESSION["cart"];
				if(!empty($cart)){
					$user_id= $user->id;

					$items = explode(',',$cart);
					$contents = array();

					foreach ($items as $item) {
						$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
					}

	    			$total_cost = $_SESSION['total'];

					//Getting the product id from the array
					$k = array_keys($contents);
					$prod_id = implode(',',$k);

					//Getting the product quantity from the array
					$v = array_values($contents);
					$prod_quantity = implode(',',$v);


					$check_user = $this->getCheckuser($user_id);

					if(empty($check_user))
					{
						$query		= $db->getQuery(true);
						$query->insert("#__jegroupbuy_addtocart");
						$query->set("uid =".$user_id);
						$query->set("prod_id='".$prod_id."'");
						$query->set("pro_quantity='".$prod_quantity."'");
						$query->set("total_cost=".$total_cost);
						$db->setQuery($query);

						if (!$db->query()) {
							JError::raiseError(500, $db->getErrorMsg());
						}
					} else {
						$query		= $db->getQuery(true);
						$query->update('#__jegroupbuy_addtocart');
						$query->set("prod_id='".$prod_id."'");
						$query->set("pro_quantity='".$prod_quantity."'");
						$query->set("total_cost=".$total_cost);
						$query->where('uid='.(int)$user_id);
						$db->setQuery($query);

						if (!$db->query()) {
							JError::raiseError(500, $db->getErrorMsg());
						}
					}

				} else {
					$red_url = "index.php?option=com_jegroupbuy&view=jegroupbuy";
					$controller->setMessage("There are no products found in the cart");
					$controller->setRedirect($red_url);
				}
			}

			$val["id"] = $prod_id;
			$val["quan"] = $prod_quantity;
			$val["total"]=$total_cost;

			$options = $val["id"].":".$val["quan"].":".$val["total"];

			if(!empty($options)){
				JPluginHelper::importPlugin( 'jegroupbuypayment' );
				$dispatcher =& JDispatcher::getInstance();
				$PaymentMethodDetails = $dispatcher->trigger( 'onPaymentMethodList',$options);
				$plugin_info = JPluginHelper::getPlugin('jegroupbuypayment', $plugin=null);
				$PaymentMethodMessage="";
				$message="";


				if($action=="showresult")
				{
					$inv_arg["inv_id"] = $id;
					$arg = ($inv_arg);
					$PaymentMethodMessage = $dispatcher->trigger( 'onAfterFailedPayment',$arg);
					$message=$this->getPaymentPluginStatus($PaymentMethodMessage,$plugin_info,$ptype);
				}

				$this->assignRef("PaymentMethodDetails",$PaymentMethodDetails);
				$this->assignRef("plugin_info",$plugin_info);
				$this->assignRef("result",$result);
			}

		} else {

			JPluginHelper::importPlugin("jegroupbuypayment");
			$dispatcher =& JDispatcher::getInstance();
			$results = $dispatcher->trigger( 'onProcessPayment');
			$text = trim(implode("\n", $results));
			echo $text;
		}
		$this->_prepareDocument();

		parent::display( $tpl );
	}

	/**
	 * Prepares the document
	 */
	protected function _prepareDocument()
	{
		$app		= JFactory::getApplication();
		$menus		= $app->getMenu();
		$pathway	= $app->getPathway();
		$title		= null;
		$params 	= $app->getParams();
		$menu		= $menus->getActive();

		// because the application sets a default page title, we need to get it
		// right from the menu item itself
		if (is_object($menu)) {
			$menu_params = new JRegistry;
			$menu_params->loadJSON($menu->params);
			if (!$menu_params->get('page_title')) {
				$params->set('page_title',	JText::_('COM_JEGROUPBUY_TITLE_PAYMENT_DETAILS_LIST'));
			}
		}
		else {
			$params->set('page_title',	JText::_('COM_JEGROUPBUY_TITLE_PAYMENT_DETAILS_LIST'));
		}

		$title = $params->get('page_title');
		if ($app->getCfg('sitename_pagetitles', 0)) {
			$title = JText::sprintf('JPAGETITLE', $app->getCfg('sitename'), $title);
		}

		$this->document->setTitle($title);
	}

	function limit_characters ( $str, $n )
	{
		if ( strlen ( $str ) <= $n )
		{
			return $str;
		}
		else {
			return substr ( $str, 0, $n ) . '...';
		}
	}

	public function getCheckuser($uid)
	{
		// Connect db
		$db			= JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->select('uid');
		$query->from('#__jegroupbuy_addtocart');
		$query->where('uid = '.(int) $uid);
		$db->setQuery($query);
		$result = $db->loadResult();

		return $result;
	}

	function getPaymentPluginStatus($PaymentMethodMessage,$plugin_infos,$ptype)
	{
		$i = 0;
		foreach($PaymentMethodMessage as $PaymentMethodMessages)
		{

			if($plugin_infos[$i]->name == $ptype)
			{
				return $PaymentMethodMessages;
			}
			$i++;
		}
	}
}
