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

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

jimport('joomla.application.component.model');
JLoader::import('components.com_jlticketcenter.helpers.jlticketcenter',JPATH_ADMINISTRATOR);

class JLTicketCenterModelOrder extends JModelLegacy
{
	var $_data;
	var $_total = null;
	var $_pagination = null;


	function __construct()
	{
		parent::__construct();

		$mainframe = JFactory::getApplication();

		// Get pagination request variables
		$limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
		$limitstart = JRequest::getVar('limitstart', 0, '', 'int');

		// In case limit has been changed, adjust it
		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);

		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);

		// Order By
		$context			= 'com_jlticketcenter.order.list.';
		$filter_order     = $mainframe->getUserStateFromRequest($context.'filter_order','filter_order','o.`order_id`','cmd');
		$filter_order_Dir = $mainframe->getUserStateFromRequest($context.'filter_order_Dir','filter_order_Dir','desc','word');

		$this->setState('filter_order', $filter_order);
		$this->setState('filter_order_Dir', $filter_order_Dir);

		if (!class_exists(GENERAL_MODEL)){
			include 'ticketscenter.php';
		}

		$model = JModelLegacy::getInstance('General', 'JLTicketCenterModel');
		$model->OrderStatusList();

	}


	/**
	 * Returns the query
	 * @return string The query to be used to retrieve the rows from the database
	 */
	function _buildQuery()
	{
		$filter = JRequest::getVar( 'filter', null );// LOWER;

		if (isset($filter['search']) && $filter['search']>''){
			$search =$filter['search'];

			$search = strtolower($search);
			$where[] = "(LOWER(o.`venue_name`) LIKE '%".$search."%' OR LOWER(city.`city_name`) LIKE '%".$search."%' OR LOWER(country.`country`) LIKE '%".$search."%')";
		}
		if (isset($filter['state']) && $filter['state']>''){
			if ($filter['state']=='U'){
				$where[] = "o.`published`=0";
			}else{
				$where[] = "o.`published`=1";
			}
		}


		if (isset($filter['country'])&& $filter['country']>''){
			$where[] = "o.`country_id`='".$filter['country']."'";
		}

		if (isset($filter['states'])&& $filter['states']>''){
			$where[] = "o.`state_id`='".$filter['states']."'";
		}

		if (isset($filter['city'])&& $filter['city']>''){
			$where[] = "o.`city_id`='".$filter['city']."'";
		}

		if (isset($filter['order_id'])&& $filter['order_id']>''){
			$where[] = "o.`order_id`='".$filter['order_id']."'";
		}

		if (isset($filter['status'])){
			$where[] = "o.`status`='".$filter['status']."'";
		}



		$query = 'SELECT *'
		. ' FROM #__jltcenter_order o'
		.' JOIN #__jltcenter_users c ON c.`id`=o.`client_id`';

		if (isset($where)){
			$query .=" WHERE ".implode(' AND ',$where);
		}

		$query .= $this->_buildEventsOrderBy();

		//echo $query ;
		return $query;
	}


	function _buildEventsOrderBy()
	{
		$mainframe = JFactory::getApplication();

		$orderby = '';
		$filter_order     = $this->getState('filter_order');
		$filter_order_Dir = $this->getState('filter_order_Dir');

		/* Error handling is never a bad thing*/
		if(!empty($filter_order) && !empty($filter_order_Dir) ){
			$orderby = ' ORDER BY '.$filter_order.' '.$filter_order_Dir;
		}
		return $orderby;
	}


	function getData()
	{
		if (empty($this->_data)) {
			$query = $this->_buildQuery();

			$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
		}
		return $this->_data;
	}

	 
	function getTotal()
	{
		if (empty($this->_total)) {
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}
		return $this->_total;
	}
	 

	function getPagination()
	{
		if (empty($this->_pagination)) {
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}
		return $this->_pagination;
	}


	/**
	 * Method to store a record
	 *
	 * @access	public
	 * @return	boolean	True on success
	 */
	function store($data)
	{


		// Collect Cleint Data

		$client = $data;
		$client['id'] =  $client['client_id'];
		unset ($client['order_status'],
		$client['order_total'],
		$client['manager_remark'],
		$client['delivery_method'],
		$client['delivery_rate'],
		$client['payment_method'],
		$client['created'],
		$client['order_ip'],
		$client['client_id']
		);

		$client_row =& $this->getTable('JLTCenterUsers');


		if (!$client_row->bind($client)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}


		if (!$client_row->check($client)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		if (!$client_row->store()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}



		//var_dump($client );
		//die;


		unset ($data['first_name'],
		$data['last_name'],
		$data['phone_num'],
		$data['street'],
		$data['city'],
		$data['state'],
		$data['country'],
		$data['email'],
		$data['option'],
		$data['task'],
		$data['controller'],
		$data['zip_code']

		);

		//var_dump($data);
		//die;



		$row =& $this->getTable();

		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( $row->getErrorMsg() );
			return false;
		}
			


		return true;
	}

	function delete()
	{
		$cids = JRequest::getVar( 'order_id', array(0), 'post', 'array' );

		$row =&$this->getTable();

		if (count( $cids )) {
			foreach($cids as $cid) {
				if (!$row->delete( $cid )) {
					$this->setError( $row->getErrorMsg() );
					return false;
				}
			}
		}
		return true;
	}


	function orderStatusDrop($status_value=0,$name='order_status'){

		$options = array();

		$options[] = JHTML::_('select.option', JLTCENTER_PENDING,JText::_('Pending'));
		$options[] = JHTML::_('select.option', JLTCENTER_PAID,JText::_('Paid'));
		$options[] = JHTML::_('select.option', JLTCENTER_SENT,JText::_('Sent'));
		$options[] = JHTML::_('select.option', JLTCENTER_CANCEL,JText::_('Cancel'));

		//$dropdown = JHTML::_('select.genericlist',   $options, $name, 'class="inputbox" size="'. $size .'" '. $javascript, 'value', 'text', $status_value);
		$dropdown = JHTML::_('select.genericlist',   $options, $name, 'class="inputbox" ', 'value', 'text', $status_value);

		return  $dropdown;

	}

	public static function getOrderStatus($status_value=0){
		switch ($status_value){
			case JLTCENTER_PAID:
				return JText::_('Paid');
				break;
					
			case JLTCENTER_SENT:
				return JText::_('Sent');
				break;
					
			case JLTCENTER_CANCEL:
				return JText::_('Cancel');
				break;
					
			default:
				return JText::_('Pending');
				break;
		}
	}

	function getOrderLines(){
		$filter = JRequest::getVar( 'filter', null );// LOWER;


		$where[] = "ol.`order_id`='".$filter['order_id']."'";
			
		$query = 'SELECT ol.*,e.`event_name`,e.`event_date`,e.`event_type`,e.`ticket_template`,p.`performer_name`,v.`venue_name`,city.`city_name`,state.`state_name`,country.`country`  AS `country`,ticket_type.`ticket_desc` '
		. ' FROM #__jltcenter_order_lines ol';
			
		$query .= " LEFT JOIN #__jltcenter_events  e  ON e.`id`=ol.`event_id` ";
		$query .= " LEFT JOIN #__jltcenter_performer p  ON p.`id`=e.`performer_id` ";
		$query .= " LEFT JOIN #__jltcenter_venue v  ON v.`id`=e.`venue_id` ";
		$query .= " LEFT JOIN #__jltcenter_city city  ON city.`id`=e.`city_id` ";
		$query .= " LEFT JOIN #__jltcenter_state state  ON state.`id`=e.`state_id` ";
		$query .= " LEFT JOIN #__jltcenter_country country ON country.`id`=e.`country_id` ";
		$query .= " LEFT JOIN #__jltcenter_events_ticket_type ticket_type ON ticket_type.`ticket_type`=ol.`ticket_type` ";

		if ($where){
			$query .=" WHERE ".implode(' AND ',$where);
		}

		$this->_db->setQuery( $query);
		$result = $this->_db->loadObjectList();

		return $result;
	}//EOF getOrderLines;


	function emailOrder($orderId=0,$data=array(),$bcc_admin=false){

		JLTicketCenterHelper::loadFrontLang();

		if ($orderId==0 && !$data){
			return;
		}

		if ($data){
			$order = $data;
			$filter['order_id'] =$data['order_id'];
			JRequest::setVar('filter', $filter);
				
			$order_lines = self::getOrderLines();
				
		}else{
			$filter['order_id'] =$orderId;
			JRequest::setVar('filter', $filter);
			$order		= & $this->get('Data');
			$order		= self::getData();
			$order		= $order[0];
			$order_lines = self::getOrderLines();
		}


		$params = new JLTicketCenterHelperSetup;

		$db =& JFactory::getDBO();
		$query = "SELECT  *
				 FROM `#__jltcenter_delivery_method`
				 WHERE `id`=".$order['delivery_method'];
		$db->setQuery($query);
			
		$delivery_result = $db->loadObject();
		if (!empty($delivery_result )){
			$delivery_method =$delivery_result->name;
		}
			
		$query = "SELECT  *
				 FROM `#__jltcenter_payment_method`
				 WHERE `id`=".$order['payment_method'];
		$db->setQuery($query);
		$payment_result = $db->loadObject();
		if(!empty($payment_result)){
			$payment_method =$payment_result->name;
		}

		$config =& JFactory::getConfig();
		ob_start();
		include JPATH_ADMINISTRATOR.'/components/com_jlticketcenter/views/order/tmpl/email_order.php';
		$mailBody = ob_get_contents();
		ob_end_clean();
			
		$mailData = array('email'=> $order['email'],
  						  'subject'=>JText::_('JLTC_ORDER_MAIL_SUBJECT').' '.$order['order_id'],
  						  'body'=>$mailBody);

		if ($bcc_admin){
			$pparams = new JLTicketCenterHelperSetup;
			$mailData['bcc'] = $pparams->get('bcc_order_to_admin');

		}



		self::sendMail($mailData);


		return;
	}

	public static function getDeliveryMethods($method_id=0){

		$pparams = new JLTicketCenterHelperSetup;

		$session = JFactory::getSession();
		$seesion_id = $session->getId();
			
		$data = $session->get('jlticketcenter_cart_detials');


		$default=$method_id;
		$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 (!$default || $method->id==$session->get('JLTicketCenter_delivery' || $method->id==$method_id)){
	  	 
				self::$delivery_price = $method->price;
			}
		}

		$radio = JHTML::_('select.genericlist', $options, 'delivery_method', 'class="delivery_method"', 'value', 'text', $default);

		return $radio;
	} //EOF getDeliveryMethods


	function updateStatus($data){

		switch ($data['new_status']){
			case 'OrderPaid':
				$status = JLTCENTER_PAID;
				break;
			case 'OrderSent':
				$status = JLTCENTER_SENT;
				break;
			case 'OrderCancel':
				$status = JLTCENTER_CANCEL;
				break;
					
		}
		$db =& JFactory::getDBO();
		$query="UPDATE #__jltcenter_order
				SET `order_status`=".$status .",
					`modified`=NOW()
				WHERE `order_id`=".$data['order_id'];
		$db->setQuery($query);
		//echo $db->getQuery();
		$db->Query();

		return;
	}

	function updateEventsTickets($data){
		$filter['order_id'] =$data['order_id'];
		JRequest::setVar( 'filter', $filter);
		$order_lines = self::getOrderLines();

		$db =& JFactory::getDBO();

		foreach ($order_lines  as $line){
			if ($data['new_status']=='OrderPaid'){
				$query="UPDATE #__jltcenter_events_ticket_type
						SET `tickets_sold`=`tickets_sold`+".$line->quantity.",
							`tickets_ordered`=IF(`tickets_ordered`>0,`tickets_ordered`-".$line->quantity.",0)
						WHERE `ticket_type`=".$line->ticket_type;
			}
			else{
				// Cancel

				if ($data['order_status']==JLTCENTER_PAID ||$data['order_status']==JLTCENTER_SENT){
					$query="UPDATE #__jltcenter_events_ticket_type
							SET `tickets_sold`=`tickets_sold`-".$line->quantity."
							WHERE `ticket_type`=".$line->ticket_type;
				}else{
					$query="UPDATE #__jltcenter_events_ticket_type
							SET `tickets_ordered`=IF(`tickets_ordered`>0,`tickets_ordered`-".$line->quantity.",0)
							WHERE `ticket_type`=".$line->ticket_type;
				}
			}
				
			$db->setQuery($query);
			$db->Query();
		}

		return;
	}


	function getDeliveryMethod($method_id){

		$db = JFactory::getDBO();
		$query = "SELECT  *
				 FROM `#__jltcenter_delivery_method`
				 WHERE `id`=$method_id";

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

		return $result;
	}

	function sendMail($mailData){

		//create mail body
		$mailer =& JFactory::getMailer();
		$config =& JFactory::getConfig();
			
		$sender = array(
		$config->get('config.mailfrom'),
		$config->get('config.fromname')
		);

		$mailer->setSender($sender);
		$mailer->addRecipient($mailData['email']);

		$pparams = new JLTicketCenterHelperSetup;

		$mailer->setSubject($mailData['subject']);
		$mailer->isHTML(true);
		$mailer->setBody($mailData['body']);

		if(!empty($mailData['bcc'])){
			$mailer->AddBCC($mailData['bcc']);
		}

		if (!empty($mailData['attachment'])){
			$mailer->addAttachment($mailData['attachment']);
		}

		$send = &$mailer->Send();

		if ($send !== true){
			return false;
		}

		return true;

	} //EOF sendMail


	function getUserMail(&$order){
		$user =&JFactory::getUser($order->user_id);
		$order->email = $user->email;
		return;
	}

	function cancel()
	{
		$row =& $this->getTable();
		$row->bind(JRequest::get('post'));
		$row->checkin();
		return;
	}

} // EOC