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

// No direct access
defined('_JEXEC') or die;

jimport('joomla.application.component.controller');

jimport('joomla.filesystem.file');
jimport('joomla.filesystem.archive');
jimport( 'joomla.filesystem.folder' );

require_once(JPATH_COMPONENT.DS.'assets'.DS.'tcpdf'.DS.'tcpdf.php');

/**
 * JE GroupBuy Component Controller
 */
class jegroupbuyController extends JController
{
	/**
	 * Method to display a view.
	 */
	public function display($cachable = false, $urlparams = false)
	{

		$cachable	= true;
		$user		= JFactory::getUser();
		$pid 		= JRequest::getInt("pid","");
		/*if ( $user->get('guest')) {
			if($pid > 0)
			{
				$url = base64_encode(JRoute::_('index.php?option=com_jegroupbuy&view=productdetails&pid='.$pid));
			}else
			{
				$url = base64_encode(JRoute::_('index.php?option=com_jegroupbuy&view=jegroupbuy'));
			}
			$link = "index.php?option=com_users&view=login&return=".$url;
			$this->setRedirect( $link);
		}
		*/
		// Get the document object.
			$document	= JFactory::getDocument();

		// Set the default view name and format from the Request.
			$vName		= JRequest::getCmd('view', 'faqs');
			JRequest::setVar('view', $vName);

		$user			= JFactory::getUser();

		$safeurlparams = array('catid'=>'INT','id'=>'INT','cid'=>'ARRAY','year'=>'INT','month'=>'INT','limit'=>'INT','limitstart'=>'INT',
			'showall'=>'INT','return'=>'BASE64','filter'=>'STRING','filter_order'=>'CMD','filter_order_Dir'=>'CMD','filter-search'=>'STRING','print'=>'BOOLEAN','lang'=>'CMD');

		parent::display($cachable,$safeurlparams);

		return $this;
	}

	function addComments()
	{
		$db 	= JFactory::getDBO();
		$comment= JRequest::getVar("comment", '', '', 'string', JREQUEST_ALLOWRAW);
		$user	=JFactory::getUser();
		$pid 	= JRequest::getInt("pid","");
		$cdate 	= time();
		$sql 	= "INSERT INTO  #__jegroupbuy_comments (`pid`,`uid`,`comments`,`cdate`) values ('".$pid."','".$user->id."',".$db->Quote($comment).",'".$cdate."');";
		$db->setQuery($sql);
		$db->query();

		$sql = "SELECT c.*,u.name FROM #__jegroupbuy_comments AS c LEFT JOIN #__users AS u ON u.id = c.uid  WHERE c.pid='".$pid."' ORDER BY c.cdate DESC";
		$db->setQuery($sql);
		$rows = $db->loadObjectList();
		?>
		<table cellpadding="0" cellspacing="0" width="100%">
			<tr>
		<?php
		$k = 0;
		$bgclr = '';
		foreach($rows AS $row)
		{
		if($k == 0)
		{
			$bgclr = "#F8F8F8";
		}else
		{
			$bgclr = "#FAFDF5";
		}
		?>
		<tr>
			<td style="border: 1px solid rgb(0, 0, 0);background-color:<?php echo $bgclr; ?>;border-color:#F1F1F1;padding:5px 15px 5px 10px;">
				<table cellpadding="0" cellspacing="0" width="100%">
					<tr>
						<td width="50%" style="padding:5px;border-bottom:dotted 1px #999999;">
							<b><?php echo $row->name; ?></b>&nbsp; <i><?php echo JHTML::_('date',  $row->cdate, "d-m-Y"); ?></i>
						</td>
					</tr>
					<tr>
						<td width="100%" style="padding:5px;">
							<?php
								$comments =  chunk_split ($row->comments,80, "<br/>");
								echo $comments;

							?>
						</td>
					</tr>
					<tr>
						<td>&nbsp;</td>
					</tr>
				</table>
			</td>
		</tr>
		<tr>
			<td>&nbsp;</td>
		</tr>
		<?php
			$k = 1 - $k;
		}
		?>
		</table>
		<?php
		exit;
	}

	function changeToExpired()
	{
		$db		= JFactory::getDBO();
		$pID	= JRequest::getInt("pID","");
		$sql	= "UPDATE #__jegroupbuy_product SET expired = 1 WHERE id=".$pID;
		$db->setQuery($sql);
		$db->query();
		echo $pID;
		exit;
	}

	function addtoCart()
	{
		$pid = JRequest::getInt("pid","");
		JRequest::setVar("view","productdetails");
		JRequest::setVar("layout","addcart");
		JRequest::setVar("pid",$pid);
		parent::display();
	}

	function processPayment()
	{
		JRequest::setVar( 'view', 'paymentdetails' );
		JRequest::setVar( 'layout', 'process' );
		parent::display();
	}

	function paymentDetails()
	{
		$pid 	= JRequest::getInt("pid","");
		JRequest::setVar("view","paymentdetails");
		JRequest::setVar("layout","default");
		JRequest::setVar("pid",$pid);
		parent::display();
	}

	function paymentReturnUrl()
	{

		$db 	= JFactory::getDBO();
		$user	= JFactory::getUser();

		unset ($_SESSION['cart'],$_SESSION['total']);
		$this->setRedirect(JRoute::_('index.php?option=com_jegroupbuy&view=couponpage&result=succ'));
	}
	
	function paymentReturnBank()
	{
		$db 	= JFactory::getDBO();
		$user	= JFactory::getUser();
		unset ($_SESSION['cart'],$_SESSION['total']);
		$this->setRedirect(JRoute::_('index.php?option=com_jegroupbuy&view=jegroupbuy'));
	}	
	
	public function createzip($files_name,$pid)
	{
		$app		= JFactory::getApplication();
		$config		= JComponentHelper::getParams('com_jegroupbuy');
	 	$invoice_path	= JPATH_COMPONENT.DS.'invoices'.DS.$files_name;

	    $files = $files_name;

	 	foreach ($files as $file) {
			$data = JFile::read(JPATH_COMPONENT.DS.'invoices'.DS.$file);
		}

		 header("Content-Disposition: attachment; filename=$files_name");
		 header("Pragma: public");
		 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		 header("Cache-Control: public");
		 header("Content-Description: File Transfer");
		 header("Content-type: application/pdf");
		 header("Content-Transfer-Encoding: binary");
		 header("Expires: 0");
		 ob_end_flush();
		 readfile("$invoice_path");
	 }
	 
	 
	 function downloadPdf(){
		$app		= JFactory::getApplication();
		$config		= JComponentHelper::getParams('com_jegroupbuy');
		$db 		= JFactory::getDBO();
		$user		= JFactory::getUser();
		$pro_id 	= JRequest::getVar('id');
		$query		= $db->getQuery(true);

		$query = 'SELECT id FROM #__jegroupbuy_payment where p_id='.$pro_id.' AND user_id='.$user->id.' AND method="'.JText::_("FREE_COUPON").'"';
		$db->setQuery( $query );
		$pay_record = $db->loadResult();

		if(empty($pay_record))
		{
			if(!$user->get('guest')){

				$ptype 		= JText::_("FREE_COUPON");
				$pdate 		= gmdate("Y-m-d H:i:s");
				$text_time 	= substr(time(),-6);
				$txn_id 	= rand(1000, 9000).$text_time;

				$query = 'INSERT INTO #__jegroupbuy_payment ( p_id,user_id,method , transaction_id , pdate, status,quantity)' .
						' VALUES ( "'.$pro_id.'" ,"'.$user->id.'","'.$ptype.'","'.$txn_id.'" ,"'.$pdate.'" ,"0","1" )';
				$db->setQuery( $query );
				$db->execute();

				$query = 'SELECT deal_to_date FROM #__jegroupbuy_product where id='.$pro_id;
				$db->setQuery( $query );
				$exp_date = $db->loadResult();

				$expdate = JHTML::_('date',  $exp_date, "d/m/Y");

				$query = "SELECT * FROM #__jegroupbuy_payment WHERE user_id=".$user->id." AND p_id=".$pro_id;
				$db->setQuery( $query );
				$res = $db->loadObject();

				if(JFolder::exists(JPATH_COMPONENT.DS.'invoices'.DS.'zip')){
					JFolder::delete(JPATH_COMPONENT.DS.'invoices'.DS.'zip');
				}

				$i				= rand(5, 7);

				$pdf = new PDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, false, 'ISO-8859-1', false);

				$shop = $this->shopdetails($pro_id);

				$symbol = $this->currency_symbols($shop->currencysymbol);

				$invoices		= new stdClass();

				if($config->get('pdf_logo') == null)
				{
					$image		= JPATH_SITE.DS.'components'.DS.'com_jegroupbuy'.DS.'assets'.DS.'images'.DS.'background'.DS.'joomla_logo_black.jpg';
				} else {
					$image		= JPATH_SITE.DS.$config->get('pdf_logo');
				}

				if($shop->imageurl == "" || !$shop->imageurl)
				{
					$invoices->image = JPATH_SITE.DS.'components'.DS.'com_jegroupbuy'.DS.'assets'.DS.'images'.DS.'shopping.jpg';
				}else{
					$invoices->image= JURI::root().$shop->imageurl;
				}

				$invoices->shopname		= ucfirst($shop->shop_name);
				$invoices->owner		= ucfirst($shop->owner);
				$invoices->address		= $shop->address;
				$invoices->expire		= $expdate;
				$invoices->phone		= $shop->contact_number;
				$invoices->offer		= ucfirst($shop->title);
				$invoices->offerprice	= $shop->deal_price." ".$symbol;
				$invoices->client		= ucfirst($user->name);
				$invoices->ccode		= $res->transaction_id;
				$invoices->description	= strip_tags($shop->description);

				$pdf->setPrintHeader(false);

				$pdf->AddPage();
				//{logo}

				$image_path_tmp_abs = "";

				$logo = '';

				@$image_path_tmp_abs = $image;

				if(JFile::exists($image_path_tmp_abs))
				{
					$image_path_tmp 		= $image;
				}

				$logo = '<img src="'.$image_path_tmp.'" title="'.$image_path_tmp.'" broder= "0" width="'.$config->get('pdf_logo_width').'px" height="'.$config->get('pdf_logo_height').'px"/>';

				$pdf->writeHTML($logo, true, false, true, false, 'C');

				//Data loading
				$pdf->SetFont('Times','',16);

				$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);

				$data		= $pdf->loadData($invoices, $i);

				$inv_id		= $config->get('pdf_prefix').time().$i;

				// Generate PDF
				$invoice_path	= JPATH_COMPONENT.DS.'invoices'.DS.$inv_id.'.pdf';

				$pdf->Output($invoice_path, 'F');

				$files_name		= $inv_id.'.pdf';

				$this->createzip($files_name,$pro_id);

			//$app->redirect(JRoute::_('index.php?option=com_jegroupbuy&view=jegroupbuy'),JText::_("Downloaded Successfully"));

			} else {
				$send_mail = base64_encode(JRoute::_('index.php?option=com_jegroupbuy&view=productdetails&pid='.(int) $pro_id));
				$link = JRoute::_('index.php?option=com_users&view=login&return='.$send_mail);
				$app->redirect($link ,JText::_("PLEASE_LOGIN"),'warning');
			}
		} else {
			$link = JRoute::_('index.php?option=com_jegroupbuy&view=jegroupbuy');
			$app->redirect($link ,JText::_("ALREADY_BOUGHT"),'warning');
		}
	}


	function cdownload(){

		$app		= JFactory::getApplication();
		$config		= JComponentHelper::getParams('com_jegroupbuy');
		$db 		= JFactory::getDBO();
		$user		= JFactory::getUser();
		$pid 		= JRequest::getVar('id');
		$date		= JFactory::getDate();

		//Get the expiry date of product from product table
		$query = 'SELECT deal_to_date FROM #__jegroupbuy_product where id='.$pid;
		$db->setQuery( $query );
		$exp_date = $db->loadResult();

		$expdate = JHTML::_('date',  $exp_date, "d/m/Y");

		if(!$user->get('guest')){

			$query = "SELECT * FROM #__jegroupbuy_payment WHERE user_id=".$user->id." AND  p_id=".$pid;
			$db->setQuery( $query );
			$res = $db->loadObject();

			if(JFolder::exists(JPATH_COMPONENT.DS.'invoices'.DS.'zip')){
				JFolder::delete(JPATH_COMPONENT.DS.'invoices'.DS.'zip');
			}

			$i				= rand(5, 7);
		
			$pdf = new PDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, false, 'ISO-8859-1', false);

			$shop = $this->shopdetails($pid);

			$symbol = $this->currency_symbols($shop->currencysymbol);

			$invoices		= new stdClass();

			if($config->get('pdf_logo') == null)
			{
				$image		= JPATH_SITE.DS.'components'.DS.'com_jegroupbuy'.DS.'assets'.DS.'images'.DS.'background'.DS.'joomla_logo_black.jpg';
			} else {
				$image		= JPATH_SITE.DS.$config->get('pdf_logo');
			}

			if($shop->imageurl == "" || !$shop->imageurl)
			{
				$invoices->image = JPATH_SITE.DS.'components'.DS.'com_jegroupbuy'.DS.'assets'.DS.'images'.DS.'shopping.jpg';
			}else{
				$invoices->image= JURI::root().$shop->imageurl;
			}
			
			$invoices->shopname		= ucfirst($shop->shop_name);
			$invoices->owner		= ucfirst($shop->owner);
			$invoices->address		= $shop->address;
			$invoices->expire		= $expdate;
			$invoices->phone		= $shop->contact_number;
			$invoices->offer		= ucfirst($shop->title);
			$invoices->offerprice	= $shop->deal_price." ".$symbol;
			$invoices->client		= ucfirst($user->name);
			$invoices->ccode		= $res->transaction_id;
			$invoices->description	= strip_tags($shop->description);

			$pdf->setPrintHeader(false);

			$pdf->AddPage();
			//{logo}

			$image_path_tmp_abs = "";

			$logo = '';

			@$image_path_tmp_abs = $image;

			if(JFile::exists($image_path_tmp_abs))
			{
				$image_path_tmp 		= $image;
			}

			$logo = '<img src="'.$image_path_tmp.'" title="'.$image_path_tmp.'" broder= "0" width="'.$config->get('pdf_logo_width').'px" height="'.$config->get('pdf_logo_height').'px"/>';

			$pdf->writeHTML($logo, true, false, true, false, 'C');

			//Data loading
			$pdf->SetFont('Times','',16);

			$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);

			$data		= $pdf->loadData($invoices, $i);

			$inv_id		= $config->get('pdf_prefix').time().$i;

			// Generate PDF
			$invoice_path	= JPATH_COMPONENT.DS.'invoices'.DS.$inv_id.'.pdf';

			$pdf->Output($invoice_path, 'F');

			$files_name		= $inv_id.'.pdf';

			$this->createzip($files_name,$pid);

		//$app->redirect(JRoute::_('index.php?option=com_jegroupbuy&view=jegroupbuy'),JText::_("Downloaded Successfully"));

		} else {
			$send_mail = base64_encode(JRoute::_('index.php?option=com_jegroupbuy&view=productdetails&pid='.(int) $pid));
			$link = JRoute::_('index.php?option=com_users&view=login&return='.$send_mail);
			$app->redirect($link ,JText::_("PLEASE_LOGIN"),'warning');
		}
	}

	function currency_symbols($sym)
	{
		if($sym == "&#36") $symbol = "USD";
		elseif($sym == "&#163") $symbol = "GBP";
		elseif($sym == "&#165") $symbol = "JPY";
		elseif($sym == "&#128") $symbol = "EUR";
		elseif($sym == "&#8377") $symbol = "INR";
		elseif($sym == "&#36") $symbol = "AUD";
		elseif($sym == "&#36") $symbol = "CAD";
		elseif($sym == "&#36") $symbol = "NZD";
		elseif($sym == "&#67&#72&#70") $symbol = "CHF";
		elseif($sym == "&#36") $symbol = "HKD";
		elseif($sym == "&#163") $symbol = "SGD";
		elseif($sym == "&#107&#114") $symbol = "SEK";
		elseif($sym == "&#107&#114") $symbol = "DKK";
		elseif($sym == "&#122&#322") $symbol = "PLN";
		elseif($sym == "&#107&#114") $symbol = "NOK";
		elseif($sym == "&#70&#116") $symbol = "HUF";
		elseif($sym == "&#75&#269") $symbol = "CZK";
		elseif($sym == "&#8362") $symbol = "ISL";
		elseif($sym == "&#36") $symbol = "MXN";
		elseif($sym == "&#82&#36") $symbol = "BRL";
		elseif($sym == "&#82&#77") $symbol = "MYR";
		elseif($sym == "&#8369") $symbol = "PHP";
		elseif($sym == "&#78&#84&#36") $symbol = "TWD";
		elseif($sym == "&#3647") $symbol = "THB";
		else $symbol = "TRY";

		return $symbol;
	}


	function shopdetails($pid)
	{
		$db 		= JFactory::getDBO();

		$query		= $db->getQuery(true);
		$query->select('s.*, p.title,p.imageurl,p.currencysymbol,p.deal_price,p.description');
		$query->from('#__jegroupbuy_stores AS s');
		$query->leftJoin('#__jegroupbuy_product As p ON s.id = p.store_id');
		$query->where('p.id = '.$pid);
		$db->setQuery($query);
		$shop1		= $db->loadObject();

		return $shop1;
	}

	function getCouponTemplate($pid)
	{
		$db 	= JFactory::getDBO();
		$user	= JFactory::getUser();

		$sql = "SELECT pro.*,u.email,s.address,s.contact_number,py.*,s.store_logo,s.email,s.shop_url 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 src="'.JURI::root().$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;

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



// PDF Generation
class PDF extends TCPDF
{
	function loadData($invoices, $i=null)
	{
		$this->SetFont('Times','',16);
		$this->Ln(15);
		$this->Ln(0);

		$this->Cell(70);
		$this->SetFont('Times','B',16);
		$this->Cell(0,4,JText::_('SHOP_NAME'),0,0,'L');
		$this->Ln(0);
		$this->Cell(105);
		$this->SetFont('Times','',16);
		$this->Cell(0,4,$invoices->shopname,0,0,'L');
		$this->Ln(7);

		$this->Cell(70);
		$this->SetFont('Times','B',16);
		$this->Cell(0,4,JText::_('SHOP_OWNER'),0,0,'L');
		$this->Ln(0);
		$this->Cell(105);
		$this->SetFont('Times','',16);
		$this->Cell(0,4,$invoices->owner,0,0,'L');
		$this->Ln(7);

		$this->Image($invoices->image, 20, 70, "50","40");
		$this->Ln(0);

		$this->Cell(70);
		$this->SetFont('Times','b',16);
		$this->Cell(0,4,JText::_('ADDRESS'),0,0,'L');
		$this->Ln(0);
		$this->Cell(106);
		$this->SetFont('Times','',16);
		$this->Cell(0,4,$invoices->address,0,0,'L');
		$this->Ln(7);

		$this->Cell(70);
		$this->SetFont('Times','B',16);
		$this->Cell(0,4,JText::_('PHONE_NUMBER'),0,0,'L');
		$this->Ln(0);
		$this->Cell(110);
		$this->SetFont('Times','',16);
		$this->Cell(0,4,$invoices->phone,0,0,'L');
		$this->Ln(7);

		$this->Cell(70);
		$this->SetFont('Times','B',16);
		$this->Cell(0,4,JText::_('DEAL'),0,0,'L');
		$this->Ln(0);
		$this->Cell(105);
		$this->SetFont('Times','',16);
		$this->Cell(0,4,$invoices->offer,0,0,'L');
		$this->Ln(7);

		$this->Cell(70);
		$this->SetFont('Times','B',16);
		$this->Cell(0,4,JText::_('DEAL_PRICE'),0,0,'L');
		$this->Ln(0);
		$this->Cell(105);
		$this->SetFont('Times','',16);
		$this->Cell(0,4,$invoices->offerprice,0,0,'L');
		$this->Ln(7);

		$this->Cell(70);
		$this->SetFont('Times','B',16);
		$this->Cell(0,4,JText::_('EXPIRY_DATE'),0,0,'L');
		$this->Ln(0);
		$this->Cell(105);
		$this->SetFont('Times','',16);
		$this->Cell(0,4,$invoices->expire,0,0,'L');
		$this->Ln(7);

		$this->Cell(70);
		$this->SetFont('Times','B',16);
		$this->Cell(0,4,JText::_('USER'),0,0,'L');
		$this->Ln(0);
		$this->Cell(105);
		$this->SetFont('Times','',16);
		$this->Cell(0,4,$invoices->client,0,0,'L');
		$this->Ln(7);

		$this->Cell(70);
		$this->SetFont('Times','B',16);
		$this->Cell(0,4,JText::_('COUPON_CODE'),0,0,'L');
		$this->Ln(0);
		$this->Cell(107);
		$this->SetFont('Times','',16);
		$this->Cell(0,4,$invoices->ccode,0,0,'L');
		$this->Ln(20);

		$this->Cell(50);
		$this->SetFont('Times','',12);
		$this->SetY(65);
		$this->SetX(20);
		$this->MultiCell(200,25,$invoices->description,0,'L',false, 1, 20, 135, true, 0, false, true, 0, 'T', false);
		$this->Ln(0);
	}
}