<?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' );
JLoader::import('components.com_jlticketcenter.models.cart_class',JPATH_ROOT);

class JLTicketCenterModelCart extends JModelLegacy
{
	
	public $delivery_price;
	public static $payment_credit = array();
	public static $credit_open = false;
	
	function getCart(){

        $cart   = null;
		$session = JFactory::getSession();
		
		if (JRequest::getMethod()=='POST'){
			JRequest::checkToken() or die( 'Invalid Token' );
			$cart = $this->updateCart();
		}

        if ($session->get('jlticketcenter_cart_id') != null){


		$db = JFactory::getDBO();
		$query = "SELECT cart.*,cart.`id` AS `cart_line_id`,
				e.`event_name`,e.`event_date`,e.`event_type`,
				v.`venue_name`,
				ticket.`tickets`,ticket.`tickets_sold`,ticket.`tickets_sold`,ticket.`tickets_ordered`,ticket.`ticket_desc` 
				 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`
				 LEFT JOIN `#__jltcenter_events_ticket_type` ticket ON ticket.`ticket_type`=cart.`ticket_type`
				 WHERE cart.`uniqid`=".$session->get('jlticketcenter_cart_id');
		
		$db->setQuery($query);
		//echo $db->getQuery();
		
		$cart  = $db->loadObjectList();
        }

		if (!empty($cart)){
			foreach ($cart  as $cart_line){
				$ticket_type_in[] = $cart_line->ticket_price; 
			}
			
			// Check availibility
			$pparams = new JLTicketCenterHelperSetup;
			
			if ($pparams->get('cart_countdown',10)>0){
				$start_time = $pparams->get('cart_countdown',10)*60;
				
				$query = "SELECT cart.`ticket_type`,SUM(cart.`quantity`) AS `amount`
					 	  FROM `#__jltcenter_cart` cart
					 	  WHERE  cart.`ticket_price` IN (".implode(',', $ticket_type_in) .")
						  AND `add_time` BETWEEN UNIX_TIMESTAMP()-".$start_time. " AND UNIX_TIMESTAMP()
						  AND cart.`uniqid`!=".$session->get('jlticketcenter_cart_id')." 
						GROUP BY cart.`ticket_type`"; 
				$db->setQuery($query);
				
				$in_cart_results  = $db->loadObjectList();
				if(!empty($in_cart_results)){
					$in_cart = array();
					foreach ($in_cart_results as $cart_line){
						$in_cart[$cart_line->ticket_type]  = $cart_line->amount ;
					}
				}
			}//end cart check
		}
		
		JLoader::import('components.com_jlticketcenter.models.cart_class',JPATH_ROOT);
		if (!empty($cart)){
		foreach ($cart as $cart_line){
				$cart_line->in_cart = $cart_line->quantity;
				if (!empty($in_cart[$cart_line->ticket_type])){
					$cart_line->in_cart += $in_cart[$cart_line->ticket_type];
				}
				$dropdown = JLTicketCenterCart::quantityDropdown($cart_line->quantity, 'qty_'.$cart_line->id, '',$cart_line);

				$cart_line->dropdown  = $dropdown;
			}
		}
		
		return $cart;
	}
	
	private function updateCart(){
		// Session
		$session = JFactory::getSession();
		$db = JFactory::getDBO();
		

		if (JRequest::getInt('qty',0)>0){
			$data['event_id'] = JRequest::getInt('event_id',0,'post');
			
			// Add/Update Cart
			if (!$session->get('jlticketcenter_cart_id')){
				//echo "<br> 555<br>";
				$data['uniqid'] ="'".md5(uniqid('jlTicketCenter'.rand(), true))."'";
				$data['add_time'] = time();
				
				$session->set('jlticketcenter_cart_id',$data['uniqid'] );
				 
			}else{
				// get Cart Time
				$data['uniqid'] =$session->get('jlticketcenter_cart_id');
				$data['add_time'] = $this->getAddTime($data['uniqid']);
			}
			

			$data['ticket_type'] = JRequest::getInt('ticket_type',0,'post');
			
			$data['ticket_price'] = self::getTicketPrice($data['ticket_type']);
			
			
				
			if (JRequest::getFloat('price',0)==0 || is_null(JRequest::getFloat('price'))){
				$data['ticket_price'] = self::getTicketPrice($data['event_id']);
				JRequest::setVar('price',$data['ticket_price']);
			}else{
				$data['ticket_price'] = JRequest::getFloat('price',0);
			}
			
			$data['quantity'] = JRequest::getInt('qty',0);
			
			
			
			$query = "SELECT `event_type` 
				 FROM `#__jltcenter_events`
				 WHERE `id`=".$data['event_id'];
		
			$db->setQuery($query);
			$event_type = $db->loadResult();
			
			$data['event_type']=$event_type ;
                        
		}
		else{
			// Delete From Cart
			$id = JRequest::getVar('id',0);
			$query = "DELETE FROM `#__jltcenter_cart` WHERE `id`=".$id ;
		 	$db->setQuery($query);
		 	$db->Query();
		 	return ; 
		}
		
		$this->checkCartEventTypes();
		
		$query = "SELECT cart.* 
				 FROM `#__jltcenter_cart` cart
				 WHERE cart.`uniqid`=".$session->get('jlticketcenter_cart_id');
		
		$db->setQuery($query);
		
		$cartLines  = $db->loadObjectList();
		
		if (!empty($cartLines)){
			foreach ($cartLines  as $line){
				if($line->event_type != $data['event_type']){
					//Get a handle to the Joomla! application object
					$app =& JFactory::getApplication(); 
					$app->enqueueMessage( JText::_('JLTCETNER_CART_MISMATCH'), 'error');
					return;	
				}
			}	
		}
		
		$query = "INSERT INTO `#__jltcenter_cart` (`event_id`,`uniqid`,`add_time`,`ticket_type`,`ticket_price`,`quantity`,`event_type`) 
					VALUES (".implode(',', $data).")
				ON DUPLICATE KEY UPDATE `ticket_price`=VALUES(`ticket_price`),`quantity`=VALUES(`quantity`)";
		
		$db->setQuery($query);
		
		$db->Query();
                
		
		return;
	}// EOF updateCart()
	
	
	private function checkCartEventTypes(){
		
	}
	
	
	function getCartDetials($cart){
		$db =& JFactory::getDBO();
		$full_cart = array();
		foreach  ($cart as $k=>$v){
			$query = "SELECT e.*,v.`venue_name`
				 FROM `jos_jltcenter_events` e
				 LEFT JOIN `jos_jltcenter_venue` v ON v.`id`=e.`venue_id`
			     WHERE e.`id`=".$v->event_id;
			
			$db->setQuery($query);
			$cart_line = $db->LoadObject();
			
			$v->event_obj = $cart_line ; 
			$full_cart[$k]=$v;
		}
		$cart = $full_cart;
		return  $cart;
	}
	
	
	function getuserDetials(){
		
		$session = JFactory::getSession();
		$user = JFactory::getUser();

		$user_detials = new stdClass();
		$user_detials->email = '';
		$user_detials->first_name = '';
		$user_detials->last_name = '';
		$user_detials->phone_num = '';
		$user_detials->street = '';
		$user_detials->city = '';
		$user_detials->state = '';
		$user_detials->country = '';
		$user_detials->zip_code = '';
			
		if($user->id){
			$db =& JFactory::getDBO();
			
			$query = "SELECT  * 
					 FROM `#__jltcenter_users`
					 WHERE `user_id`=".$user->id; 
		
			$db->setQuery($query);
			
			$user_detials->user_id = $user->id;
			$user_detials->email   = $user->email;
			
			$user_result =  $db->LoadObject();;
			if (!empty($user_result )){
				$user_detials = $user_result ;	
			}
		}else{
			$user_detials->user_id = 0;	
		}
		
		$session_data = $session->get('jlticketcenter_cart_detials');
		
		if ($session_data){
			$user_detials->email = $session_data['email'];
			$user_detials->first_name = $session_data['first_name'];
			$user_detials->last_name = $session_data['last_name'];
			$user_detials->phone_num = $session_data['phone_num'];
			$user_detials->street = $session_data['street'];
			$user_detials->city = $session_data['city'];
			$user_detials->state = $session_data['state'];
			$user_detials->country = $session_data['country'];
			$user_detials->zip_code = $session_data['zip_code'];
		}
		 
		
		
		return $user_detials;
	}
	
	
	function getPaymentMethods(){

		$session = JFactory::getSession();
		$seesion_id = $session->getId();
			
		$data = $session->get('jlticketcenter_cart_detials');
		
		$db = JFactory::getDBO();
		$query = "SELECT  * 
				 FROM `#__jltcenter_payment_method`
				 WHERE `published`=1
				 ORDER BY `ordering`";

		$db->setQuery($query);
		$results  = $db->loadObjectList();
		
		if (!$results){
			return null;
		}
		 $options = array();
		 if ($results[0]->credit_cart==1){
		 	self::$credit_open = true;	
		 }
		 		
		 foreach($results as $method){
		 		
	  	    $options[] = JHTML::_('select.option', $method->id, $method->description);
	  	    if (!isset($default)){
	  	    	$default=$method->id;
	  	    }
	  	    
	  	    if ($method->credit_cart==1){
	  	    	self::$payment_credit[] =$method->id;
	  	    }
	 	}
	 	
	 	//self::$delivery_price;
		 
	 	if ($data['payment_method']){
	 			$default=$data['payment_method'];
	 	}
		 $radio = JHTML::_('select.radiolist', $options, 'payment_method', 'class="payment_method"', 'value', 'text', $default);

		 
		 return $radio;
	} //EOF getPaymentMethods

	
	function getDeliveryMethods(){

		$pparams = new JLTicketCenterHelperSetup;
		
		$session = JFactory::getSession();
		$seesion_id = $session->getId();
			
		$data = $session->get('jlticketcenter_cart_detials');
		
		$db = JFactory::getDBO();
		$query = "SELECT  * 
				 FROM `#__jltcenter_delivery_method`
				 WHERE `published`=1
				 ORDER BY `ordering`";

		$db->setQuery($query);
		$results  = $db->loadObjectList();
		
		if (!$results){
			return null;
		}
		 $options = array();
		 foreach($results as $method){
		 	if ($method->price>0){
		 		$methods_desc = $method->name.'  - '.$pparams->get('currency_symbol'). $method->price;
		 	}
		 	else{
		 		$methods_desc = $method->name;
		 	}
	  	    $options[] = JHTML::_('select.option', $method->id, $methods_desc );
	  	    if (!isset($default) || $method->id==$session->get('JLTicketCenter_delivery')){
	  	    	$default=$method->id;
	  	    	$this->delivery_price = $method->price;
	  	    }
	 	}
		
		 $radio = JHTML::_('select.radiolist', $options, 'delivery_method', 'class="delivery_method"', 'value', 'text', $default);

		 return $radio;
	} //EOF getDeliveryMethods
	
	
	function getDeliveryPrice(){
		return $this->delivery_price;
	}
	
	
	function getDeliveryChange(){
		$session = JFactory::getSession();
		$delivery = JRequest::getInt('delivery_method',0);

		if ($delivery==0){
			return;
		}
		$db = JFactory::getDBO();
		$query = "SELECT  * 
				 FROM `#__jltcenter_delivery_method`
				 WHERE `id`=$delivery";

		$db->setQuery($query);
		$results  = $db->loadObject();
		

		$delivery_price = number_format($results->price,2);
		
		$session->set('JLTicketCenter_delivery',$delivery); 
		$session->set('JLTicketCenter_delivery_price',$delivery_price);

		$return = $delivery_price;
		 return $return;
	} //EOF getDeliveryMethods

	
	private function getTicketPrice($ticket_type_id){

		if ((int)$ticket_type_id<=0){
			return;
		}
		$db = JFactory::getDBO();
		$query = 'SELECT t.*, e.`pre_sale_date`, e.`pre_sale_discount`
				FROM #__jltcenter_events_ticket_type t
				JOIN #__jltcenter_events e ON e.`id` = t.`event_id`
				WHERE `ticket_type`='.(int)$ticket_type_id;
		
		$db->setQuery($query);
		
		$ticket  = $db->loadObject();
		$now  = new JDate();
		if($ticket->pre_sale_date>0 && $ticket->pre_sale_date >= $now->toSql()  && $ticket->pre_sale_discount>0){
			$price = number_format($ticket->ticket_price - ($ticket->ticket_price*($ticket->pre_sale_discount/100)),2);
		}else{
			$price = $ticket->ticket_price; 
		}

                if (is_null($price)){
                    $price = 0;
                }
                
		return $price;
	}//EOF getEvent
	
	private function getAddTime($uniqid){
		$db = JFactory::getDBO();
		
		$query = "SELECT `add_time` 
				FROM #__jltcenter_cart
				WHERE `uniqid`=".$uniqid 
				." LIMIT 1";
			
		$db->setQuery($query);
		//echo $db->getQuery();
		
		$add_time  = $db->loadResult();
		
		if (!$add_time){
			$add_time= time();
		}
		
		
		return $add_time;
		
	}//EOF getAddTime

	
	function quantityDropdown($value=0,$id='qty',$class=''){
		
		 $pparams = new JLTicketCenterHelperSetup;
		 $default = $pparams->get('def_qty',2);
		 if ($value>0){
		 	$default=$value; 
		 }
		
		  $qty_array = array();
		  for ($i=1;$i<=$pparams->get('qty_max',1);$i++){
		  	$qty_array[$i]=$i;
		  } 
		  
		  $options = array();
		  foreach($qty_array  as $key=>$value) :
		  		$options[] = JHTML::_('select.option', $key, $value);
		  endforeach;

		  $dropdown = JHTML::_('select.genericlist', $options, $id, 'class="inputbox'.' '.$class.'"', 'value', 'text', $default);
		  
		  return $dropdown;
	}//EOF quantityDropdown
	
	function getCartLine(){
		$session = JFactory::getSession();
		
		$db = JFactory::getDBO();
		$query = "SELECT cart.* 
				 FROM `#__jltcenter_cart` cart
				 WHERE cart.`uniqid`=".$session->get('jlticketcenter_cart_id')
				."AND  cart.`id`=".JRequest::getVar('id',0);
		
		$db->setQuery($query);
		
		$cartLine  = $db->loadObject();
		
		return $cartLine  ;
	}
	
	function getCleanCart(){
		$session = JFactory::getSession();
		
		$db = JFactory::getDBO();
		$query = "DELETE 
				 FROM `#__jltcenter_cart`
				 WHERE `uniqid`=".$session->get('jlticketcenter_cart_id');
		
		$db->setQuery($query);
		$db->query();
		
		return;
		
	} 
	
	function getPaymentCredit(){
		return self::$payment_credit;		
	}

	function getCreditOpen(){
		return self::$credit_open;		
	}
        
        public function getCartFeildsControl(){
            $feildsStatus = array();

            $pparams = new JLTicketCenterHelperSetup;
            

            $feildsStatus['cart_first_name']= $pparams->get('cart_first_name',1);
            $feildsStatus['cart_last_name'] = $pparams->get('cart_last_name',1);
            $feildsStatus['cart_phone_num'] = $pparams->get('cart_phone_num',0);
            $feildsStatus['cart_street']    = $pparams->get('cart_street',1);
            $feildsStatus['cart_city']      = $pparams->get('cart_city',1);
            $feildsStatus['cart_state']     = $pparams->get('cart_state',0);
            $feildsStatus['cart_country']   = $pparams->get('cart_country',0);
            $feildsStatus['cart_zip_code']  = $pparams->get('cart_zip_code',0);
            $feildsStatus['cart_hear_us']   = $pparams->get('cart_hear_us',0);
            
            
            return $feildsStatus;

        }//EOF getCartFeildsStatus
	
}//EOC