<?php
/**
* @version		3.0.0
* @package		JomLand TicketCenter
* @copyright	Copyright (C) 2010 JomLand.com. All rights reserved.
* @license		GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die();

jimport('joomla.application.component.model');
jimport('joomla.utilities.date');

JLoader::import('components.com_jlticketcenter.models.cart_class',JPATH_ROOT);

class JLTicketCenterModelCheckout extends JModelLegacy
{
	
	private $_delievry_by_email = false;
	
	function getuserDetials(){
		
		$user =&JFactory::getUser();
		$db =& JFactory::getDBO();
		
		$query = "SELECT  * 
				 FROM `#__jltcenter_users`
				 WHERE `user_id`=".$user->id; 
		
		$db->setQuery($query);

		$user_detials = $db->LoadObject();
		return $user_detials;
	}
	
	function getCart(){
		
		$session = JFactory::getSession();
		
		$db = JFactory::getDBO();
		$query = "SELECT cart.*,cart.`id` AS `cart_line_id`,e.`event_name`,e.`event_date`,v.`venue_name` 
				 FROM `#__jltcenter_cart` cart
				 LEFT JOIN `#__jltcenter_events` e  ON  e.`id`=cart.`event_id`
				 LEFT JOIN `#__jltcenter_venue` v ON v.`id`=e.`venue_id`
				 WHERE cart.`uniqid`=".$session->get('jlticketcenter_cart_id');
		
		$db->setQuery($query);
		//echo $db->getQuery();
		
		$cart  = $db->loadObjectList();
		
		return $cart ;

	}//EOF getCart
	
	function cleanCart(){
		
		$session = JFactory::getSession();
		
		$db = JFactory::getDBO();
		$query = "DELETE FROM `#__jltcenter_cart` 
				 WHERE `uniqid`=".$session->get('jlticketcenter_cart_id');
		
		$db->setQuery($query);
		$db->query();
		
		$session->clear('jlticketcenter_cart_id');
		$session->clear('JLTicketCenter_delivery'); 
		$session->clear('JLTicketCenter_delivery_price');
		
		
		
		return;
	}//EOF getCart
	
	function setUserDetials(&$data){

		$user =&JFactory::getUser();
		$db =& JFactory::getDBO();
		
		JLoader::import('administrator.components.com_jlticketcenter.tables.jltcenterusers',JPATH_ROOT);
		$row =& $this->getTable('JLTCenterUsers');
		
		if ($user->id>0){
			$data['user_id'] =$user->id;
			$data['email'] =$user->email;	
		}
		
		
		if (!$row->bind($data)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		if (!$row->check($data)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		if (!$row->store()) {
			$this->setError($db->getErrorMsg());
			return false;
		}
		
		$client_id = $db->insertid();
		$data['client_id']=$client_id;
		
	}//EOF setUserDetials
	

	function getPaymentMethods(){
		
		$db =& JFactory::getDBO();
		$query = "SELECT  * 
				 FROM `#__jltcenter_payment_method`
				 WHERE `published`=1";

		$db->setQuery($query);
		$results  = $db->loadObjectList();
		
		 $options = array();
		 foreach($results as $method){
	  	    $options[] = JHTML::_('select.option', $method->id, $method->description);
	  	    if (!$default){
	  	    	$default=$method->id;
	  	    }
	 	}
		 
		 $radio = JHTML::_('select.radiolist', $options, 'payment_method', 'class="payment_method"', 'value', 'text', $default);

		 return $radio;
	} //EOF getPaymentMethods
	
	function setOrder(& $data){
		
		$session = JFactory::getSession();
		
		$user =&JFactory::getUser();
		$db =& JFactory::getDBO();
		
		JLoader::import('administrator.components.com_jlticketcenter.tables.order',JPATH_ROOT);
		$row =& $this->getTable('Order');
		 
		$data['user_id'] =$user->id;
		
		$myDate = new JDate();
		
		$data['order_ip'] = $this->getIP();  
		$data['created'] = $myDate->toSql();
		
		$order_total =0;
		$cart_total  = 0;
		$cart = $this->getCart();
		foreach ($cart  as $cart_line){
			$order_total += $cart_line->ticket_price * $cart_line->quantity;
			$cart_total += $cart_line->ticket_price * $cart_line->quantity;
		} 
		
		
		if(file_exists(JPATH_SITE.'/components/com_jlticketcenter/helpers/helper_pro.php')){
			JLoader::import('components.com_jlticketcenter.helpers.helper_pro',JPATH_SITE);
			$data['commission'] = JLTicketCenterProHelper::getCommission($cart);
		}
		else{
			$data['commission'] = 0;
		}
		
		
		if(!$session->get('JLTC_Free_event_checkout',false)){
			$data['delivery_rate'] = $this->setDeliveryRate($data); 
				
		}else{
			JLoader::import('components.com_jlticketcenter.helpers.setup',JPATH_SITE);
			$pparams = new JLTicketCenterHelperSetup;
			
			$free_delivery = $pparams->get('free_event_delivery_method');

			if(empty($free_delivery)){
				$data['delivery_method']=0;
			}else{
				$data['delivery_method']=$free_delivery;	
			}
			
			$data['payment_method']=0;
			$data['delivery_rate']=0;
		}
		
		
		$pparams = new JLTicketCenterHelperSetup;
		if ($pparams->get('tax_rate')>0){
			$tax = ($cart_total +$data['delivery_rate']+$data['commission'])*$pparams->get('tax_rate')/100;
			$data['tax'] = number_format($tax ,2);
			
		}
		else{
			$data['tax'] =0;	
		}
		
		$data['order_total'] = $cart_total +$data['delivery_rate']+$data['commission']+$data['tax'];
		
			
		if (!$row->bind($data)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		if (!$row->check($data)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		if (!$row->store()) {
			$this->setError($db->getErrorMsg());
			return false;
		}
		
		$order_id = $db->insertid();
		
		$this->setOrderLines($order_id);
		
		$data['order_id'] = $order_id;
		
		$session = JFactory::getSession();
		$seesion_id = $session->getId();
		$session->set('jlticketcenter_order_id', $order_id);
		
		
		if(!$session->get('JLTC_Free_event_checkout',false)){
			//if (!$this->_delievry_by_email){
				$this->emailOrder($data);		
			//}
		}else{
			$this->emailTicket($data);
		}
		
		
		return true;
	}//EOF setOrder;
	
	
	
	function setOrderLines($order_id){
		
		$db =& JFactory::getDBO();
		
		JLoader::import('administrator.components.com_jlticketcenter.tables.order_lines',JPATH_ROOT);
		JLoader::import('administrator.components.com_jlticketcenter.tables.events',JPATH_ROOT);
		
		$row_event =& $this->getTable('Events');
		
		$cart = $this->getCart();

		
		foreach ($cart  as $item){
			$row =& $this->getTable('JLTCenterOrderLines');
			
			$data['order_id'] = $order_id;
			$data['event_id'] = $item->event_id;
      		$data['ticket_type'] = $item->ticket_type;
      		$data['ticket_price'] = $item->ticket_price;
      		$data['quantity'] = $item->quantity;
       
      		if (!$row->bind($data)) {
				$this->setError($db->getErrorMsg());
				return false;
			}
			
			if (!$row->check($data)) {
				$this->setError($db->getErrorMsg());
				return false;
			}
			
			if (!$row->store()) {
				$this->setError($db->getErrorMsg());
				return false;
			}

			// update event order quantity 
			$query ="UPDATE #__jltcenter_events_ticket_type
					 SET `tickets_ordered`= `tickets_ordered`+".$item->quantity ."
					 WHERE `ticket_type`=".$item->ticket_type;
			$db->setQuery($query);
			$db->query();
			
      		unset ($data,$query,$row);
		} 
		
		$cart = $this->cleanCart();

		return true;
	}//EOF setOrderLines
	
	
	function getIP(){
		
	  if(!empty($_SERVER['HTTP_CLIENT_IP'])) {
	    $ip=$_SERVER['HTTP_CLIENT_IP']; // share internet
	  } elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
	    $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; // pass from proxy
	  } else {
	    $ip=$_SERVER['REMOTE_ADDR'];
	  }
	  return $ip;
	} //EOF getIP
	
	function paymentPross($data){

		$row =& JTable::getInstance('PaymentMethods', 'Table');
		$row->load($data['payment_method']);
		if ($row->published==0){
			die;
		}
		
		// get payment method
		$path = JPATH_COMPONENT_ADMINISTRATOR.DS.'models'.DS.'payment'.DS.strtolower($row->name).'.php';
		
		if (file_exists($path)) {
			require_once $path;
		} else {
			echo "Payment isn't exsit";
			return;
			die;
			//return false;
		}
		
		$class_name = 'JLTicketCenter'.$row->name;
		$payment = new $class_name;
		
		$payment->pross_payment($data);
		
		die;
	}//EOF payment_pross
	
	function setDeliveryRate(& $data){

		if ($data['delivery_method']==0){
			return;
		}
		$db =& JFactory::getDBO();
		$query = "SELECT  * 
				 FROM `#__jltcenter_delivery_method`
				 WHERE `id`=".$data['delivery_method'];

		$db->setQuery($query);
		$results  = $db->loadObject();
		
		if ($results ){
			$return = $results->price; 
			
			if($results->send_by_mail==1){
				$this->_delievry_by_email = true;
			}
		}

		return $return;
	} //EOF ggetDeliveryRate
	
	function emailOrder($data){
		// send order
		JLoader::import('components.com_jlticketcenter.models.order',JPATH_ADMINISTRATOR);
		
		$pparams = new JLTicketCenterHelperSetup;
		
		$bcc_admin =$pparams->get('bcc_order_to_admin');
		if (!is_null($bcc_admin)){
			$bcc_admin =true;
		}else{
			$bcc_admin =false;
		}
		
		JLTicketCenterModelOrder::emailOrder(0,$data,$bcc_admin);
		return;
	}
	private function emailTicket($order){
		
		$order = JArrayHelper::toObject($order);
		JLoader::import('components.com_jlticketcenter.controllers.order',JPATH_ADMINISTRATOR);

		JLTicketCenterControllerOrder::sendTicketByMail(null,$order);
		return;
	}
}//EOC