<?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.utilities.date' );

class JLTicketCenterControllerEvents extends JLTicketCenterController
{
	static public $_fb_sync_events;

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

		$pparams = new JLTicketCenterHelperSetup;
		if($pparams->get('fb_sync_events')==1 && file_exists(JPATH_ADMINISTRATOR.'/components/com_jlticketcenter/helpers/facebook_connect.php')){
			self::$_fb_sync_events=$pparams->get('fb_sync_events');
			require_once JPATH_ADMINISTRATOR.'/components/com_jlticketcenter/helpers/facebook_connect.php';
		}
		$this->registerTask('add', 'edit');
		$this->registerTask('save2copy','save');
	}


	function display($cachable = false, $urlparams = Array())
	{
		JRequest::setVar('view','events');

		parent::display();
	}

	function edit()
	{
		JRequest::setVar( 'view', 'events' );
		JRequest::setVar( 'layout', 'form'  );
		JRequest::setVar('hidemainmenu', 1);

		parent::display();
	}

	function save()
	{
		JSession::checkToken('request') or die( 'Invalid Token' );

		$task	= JRequest::getVar('task');

		//The save2copy task needs to be handled slightly differently.
		if ($task == 'save2copy') {

			$model = $this->getModel('events');
			$model->cancel();

			// Reset the ID and then treat the request as for Apply.
			$_POST['id']= 0;
			$task		= 'apply';
			foreach ($_POST['lines'] as &$line){
				$line['ticket_type']=0;
			}
		}

		$tickets_lines =$_POST['lines'];

		unset($_POST['lines']);
		$model = $this->getModel('events');

		$post	= JRequest::get('post');
		$post['description'] = JRequest::getVar('description', '', 'post', 'string', JREQUEST_ALLOWRAW);

		if(strpos($post['event_date'], '.')){
			$date_array = explode('.', $post['event_date']);
		}else{
			$date_array = explode('-', $post['event_date']);
		}

		$post['event_date']=$date_array[2].'-'.$date_array[1].'-'.$date_array[0].' '.$post['event_start'].':00';


		//var_dump($_POST);
		if (!empty($post['event_end_time'])){
			if (empty($post['event_end'])){
				$post['event_end']=$date_array[2].'-'.$date_array[1].'-'.$date_array[0].' '.$post['event_end_time'].':00';
			}else{
					
				if(strpos($post['event_end'], '.')){
					$end_date_array = explode('.', $post['event_end']);
				}else{
					$end_date_array = explode('-', $post['event_end']);
				}
					
				$post['event_end']=$end_date_array[2].'-'.$end_date_array[1].'-'.$end_date_array[0].' '.$post['event_end_time'].':00';
			}
		}




		if ($post['pre_sale_date']>''){
			if(strpos($post['pre_sale_date'], '.')){
				$pre_sale_date_array = explode('.', $post['pre_sale_date']);
			}else{
				$pre_sale_date_array = explode('-', $post['pre_sale_date']);
			}
			$post['pre_sale_date']=$pre_sale_date_array [2].'-'.$pre_sale_date_array [1].'-'.$pre_sale_date_array [0].' 00:00:00';
		}


		unset ($post['event_start'],$event_date,$post['task'],$post['controller']);


        $post = $this->checkPostData($post);


		if ($model->store($post)) {
			$msg = JText::_( 'Events Saved!' );
		} else {
			$msg = JText::_( 'Error Saving events' );
		}



        $id	= JRequest::getVar( 'id', 0, 'post');
		// Tickets Types
		JLoader::import('eventsticketstype', JPATH_ADMINISTRATOR.DS.'components'.DS.'com_jlticketcenter'.DS.'models');
		$tickets_model = JModelLegacy::getInstance('EventsTicketsType','JLTicketCenterModel');

        $tickets_model->saveLines($id, $tickets_lines);


		// Facebook Events
		$pparams = new JLTicketCenterHelperSetup;

		$now = new JDate;
		if($post['event_date'] > $now->toSql() && self::$_fb_sync_events==1 && file_exists(JPATH_ADMINISTRATOR.'/components/com_jlticketcenter/helpers/facebook_events.php')){
			require JPATH_ADMINISTRATOR.'/components/com_jlticketcenter/helpers/facebook_events.php';
			$fb_event  = new JLTicketCenterFaceBookEvents;

			$fb_event->createEvent($id,$post);

		}
		//
		//echo "<br>AFTER FB";
		//die;
		switch ($task)
		{
			case 'apply':
				$link = 'index.php?option=com_jlticketcenter&controller='.JRequest::getWord('controller').'&task=edit&cid[]='.$id;
				break;

			case 'save':
			default:
				$link = 'index.php?option=com_jlticketcenter&controller='.JRequest::getWord('controller');
				break;
		}


		$this->setRedirect($link, $msg);
	}//EOF Save

	function remove()
	{
		$model = $this->getModel('events');
		if(!$model->delete()) {
			$msg = JText::_( 'Error: One or More Cities Could not be Deleted' );
		} else {
			$msg = JText::_( 'events Deleted' );
		}

		$this->setRedirect( 'index.php?option=com_jlticketcenter&controller='.JRequest::getWord('controller'), $msg );
	}

	/**
	 * cancel editing a record
	 * @return void
	 */

	function cancel()
	{
		$model = $this->getModel('events');
		$model->cancel();

		$msg = JText::_( 'Operation Cancelled' );
		$this->setRedirect( 'index.php?option=com_jlticketcenter&controller='.JRequest::getWord('controller'), $msg );
	}


	function publish()
	{

		// Check for request forgeries
		JSession::checkToken('request') or jexit( 'Invalid Token' );

		$this->setRedirect( 'index.php?option=com_jlticketcenter&controller='.JRequest::getWord('controller'));

		// Initialize variables
		$db			=& JFactory::getDBO();
		$user		=& JFactory::getUser();
		$cid		= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$task		= JRequest::getCmd( 'task' );
		$publish	= ($task == 'publish');
		$n			= count( $cid );

		if (empty( $cid )) {
			return JError::raiseWarning( 500, JText::_( 'No items selected' ) );
		}

		JArrayHelper::toInteger($cid);
		$cids = implode(',',$cid);

		$query = 'UPDATE #__jltcenter_events'
		. ' SET `published` = ' . (int) $publish
		. ' WHERE id IN ( '. $cids.'  )'
		. ' AND ( checked_out = 0 OR ( checked_out = ' .(int) $user->get('id'). ' ) )'
		;
		$db->setQuery( $query );
		if (!$db->query()) {
			return JError::raiseWarning( 500, $db->getError() );
		}
		$this->setMessage( JText::sprintf( $publish ? 'Items published' : 'Items unpublished', $n ) );
	}


	function getCitiesOptions($where){
		$db		=&JFactory::getDBO();
		$query = "SELECT `id`,`city_name` FROM #__jltcenter_city WHERE `published`=1 AND ".$where." ORDER BY `city_name`";
		$db->setQuery($query);
		$cities = $db->LoadObjectList();

		$response ='<option val="0">'.JText::_('Select City')."</option>\n";
		foreach ($cities as $city){
			$response .='<option value="'.$city->id.'">'.$city->city_name."</option>\n";
		}

		return $response;
	}//EOF getCitiesOptions

	function getVenuesOptions($where){
		$db		=&JFactory::getDBO();

		$query = "SELECT `id`,`venue_name` FROM #__jltcenter_venue WHERE `published`=1 AND ".$where." ORDER BY `venue_name`";
		$db->setQuery($query);
		$venues = $db->LoadObjectList();

		$response ='<option val="0">'.JText::_('Select Venue')."</option>\n";
		foreach ($venues as $venue){
			$response .='<option value="'.$venue->id.'">'.$venue->venue_name."</option>\n";
		}

		return $response;
	} //getVenuesOptions

	function getCountryBoxes(){

		$country_id	= JRequest::getInt( 'id',0);
		if ($country_id	==0){
			return ;
		}

		$pparams = new JLTicketCenterHelperSetup;

		if ($pparams->get('display_state',0)>0){
			$db		=&JFactory::getDBO();
			$query = "SELECT * FROM #__jltcenter_state WHERE `published`=1 AND `country_id`=".$country_id." ORDER BY `state_name`";
			$db->setQuery($query);

			$states = $db->LoadObjectList();
			$response_state ='<option val="0">'.JText::_('Select State')."</option>\n";
			foreach ($states as $state){
				$response_state .='<option value="'.$state->id.'">'.$state->state_name."</option>\n";
			}
			$response['states']=$response_state;
		}


		$response['cities'] = $this->getCitiesOptions("`country_id`=".$country_id);
		$response['venues'] = $this->getVenuesOptions("`country_id`=".$country_id);


		echo  json_encode($response);
		return;
	}//EOF getCountryBoxes

	function getStatesBoxes(){
		$state_id = JRequest::getInt('id',0);

		if ($state_id==0){
			$response['cities'] = '';
			$response['venues'] = '';
		}else{
			$response['cities'] = $this->getCitiesOptions("`state_id`=".$state_id);
			$response['venues'] = $this->getVenuesOptions("`state_id`=".$state_id);
		}

		echo  json_encode($response);
		return;
	} // EOF getStateBoxes

	function getCitiesBoxes(){
		$city_id = JRequest::getInt('id',0);

		if ($city_id==0){
			$response['venues'] = '';
		}else{
			$response['venues'] = $this->getVenuesOptions("`city_id`=".$city_id);
		}

		echo  json_encode($response);
		return;
	} // EOF getStateBoxes

	function getVenueBoxes(){
		$venue_id = JRequest::getInt('id',0);

		if ($venue_id==0){
			$response['seats'] = '';
		}else{
			$db		=&JFactory::getDBO();
			$query = "SELECT * FROM #__jltcenter_venue WHERE `id`=".$venue_id;
			$db->setQuery($query);
			$venue = $db->LoadObject();
			$response['seats'] = $venue->seats;
		}

		echo  json_encode($response);
		return;
	} // EOF getStateBoxes


    private function checkPostData($post){

        foreach ($post as $k=>$v){
            if (empty($post[$k])){
                $post[$k]  = null;
            }
        }

        return $post;
    }


}//EOC