<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjFrontPublic extends pjFront
{
	public function __construct()
	{
		parent::__construct();
		
		$this->setAjax(true);
		
		$this->setLayout('pjActionEmpty');
	}
	

	public function pjActionLoadEvents()
	{
		$this->setAjax(true);
	
		$pjEventModel = pjEventModel::factory();
	
		$pjEventModel->where("t1.status", 'T');
	
		if(isset($_GET['category_id']) && (int) $_GET['category_id'] > 0)
		{
			$pjEventModel->where('t1.category_id', $_GET['category_id']);
		}
	
		$pjEventModel->where("(t1.category_id IN(SELECT t5.id FROM `".pjCategoryModel::factory()->getTable()."` AS t5 WHERE t5.status = 'T') OR t1.category_id IS NULL)");
		if(isset($_GET['view']) && $_GET['view'] == 'list')
		{
			if(!isset($_GET['event_id']))
			{
				list($y, $n, $j) = explode("-", date("Y-n-j"));
				$midnight = mktime(0, 0, 0, $n, $j, $y);
	
				$pjEventModel->where("t1.event_start_ts >=", $midnight);
	
				if(isset($_GET['period']) && $_GET['period'] != '' && $_GET['period'] != 'all')
				{
					$where = pjUtil::getWherePeriod($_GET['period']);
					if($where != '')
					{
						$pjEventModel->where($where);
					}
				}
	
				$total = $pjEventModel->findCount()->getData();
				$rowCount = $this->option_arr['o_events_per_page'];
				$pages = ceil($total / $rowCount);
				$page = isset($_GET['page']) && (int) $_GET['page'] > 0 ? intval($_GET['page']) : 1;
				$offset = ((int) $page - 1) * $rowCount;
				if ($page > $pages)
				{
					$page = $pages;
				}
				$pjEventModel->limit($rowCount, $offset);
				$this->set('pages', $pages);
				$this->set('page', $page);
				$this->set('paginator', array('pages' => $pages, 'total' => $total));
			}else{
				$pjEventModel->where('t1.id', $_GET['event_id']);
			}
		}else{
			$month = (int)$_GET['month'];
			$year = (int)$_GET['year'];
				
			$firstDayOfMonth = mktime(0, 0, 0, $month, 1, $year);
			$lastDayOfMonth = mktime(23, 59, 59, $month + 1, 0, $year);
				
			$pjEventModel->where("((t1.event_start_ts BETWEEN $firstDayOfMonth AND $lastDayOfMonth) OR (t1.event_end_ts BETWEEN $firstDayOfMonth AND $lastDayOfMonth) OR (t1.event_start_ts < $firstDayOfMonth AND t1.event_end_ts > $lastDayOfMonth))");
		}
	
		$event_arr = $pjEventModel
			->select("t1.*, t6.content as category, t3.content as title, t4.content as event_description, t5.content as event_location,
					(SELECT SUM(`TP`.available) FROM `".pjPriceModel::factory()->getTable()."` AS `TP` WHERE `TP`.event_id=t1.id) AS `total_avail`,
					(SELECT SUM(`TBD`.cnt) FROM `".pjBookingDetailModel::factory()->getTable()."` AS `TBD` WHERE `TBD`.booking_id IN (SELECT `TB`.id FROM `".pjBookingModel::factory()->getTable()."` as `TB` WHERE `TB`.event_id = t1.id AND (`TB`.booking_status ='confirmed' OR `TB`.booking_status ='pending') )) AS `total_booked`")
			->join('pjCategory', 't2.id=t1.category_id', 'left outer')
			->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjEvent' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'title'", 'left')
			->join('pjMultiLang', "t4.foreign_id = t1.id AND t4.model = 'pjEvent' AND t4.locale = '".$this->getLocaleId()."' AND t4.field = 'description'", 'left')
			->join('pjMultiLang', "t5.foreign_id = t1.id AND t5.model = 'pjEvent' AND t5.locale = '".$this->getLocaleId()."' AND t5.field = 'location'", 'left')
			->join('pjMultiLang', "t6.foreign_id = t1.category_id AND t6.model = 'pjCategory' AND t6.locale = '".$this->getLocaleId()."' AND t6.field = 'name'", 'left')
			->orderBy('t1.event_start_ts ASC')
			->findAll()
			->getData();
	
		$event_date_arr = array();
		foreach ($event_arr as $v)
		{
			$start_date = date('Y-m-d', $v['event_start_ts']);
			$end_date = date('Y-m-d', $v['event_end_ts']);
				
			$event_field_arr = array();
				
			$event_field_arr['id'] = $v['id'];
			$event_field_arr['event_title'] = $v['title'];
			$event_field_arr['location'] = $v['event_location'];
			$event_field_arr['category'] = $v['category'];
			$event_field_arr['event_start_ts'] = $v['event_start_ts'];
			$event_field_arr['event_end_ts'] = $v['event_end_ts'];
			$event_field_arr['event_img'] = $v['event_img'];
			$event_field_arr['event_thumb'] = $v['event_thumb'];
			$event_field_arr['o_show_start_time'] = $v['o_show_start_time'];
			$event_field_arr['o_show_end_time'] = $v['o_show_end_time'];
			$event_field_arr['total_booked'] = $v['total_booked'];
			$event_field_arr['total_avail'] = $v['total_avail'];
			$event_field_arr['description'] = $v['event_description'];
				
			if($start_date == $end_date)
			{
				$event_date_arr[$start_date][] = $event_field_arr;
			}else{
				while($start_date <= $end_date)
				{
					$event_date_arr[$start_date][] = $event_field_arr;
					$start_date = date('Y-m-d', strtotime($start_date . '+1 day'));
				}
			}
		}
	
		if(isset($_GET['view']) && $_GET['view'] == 'calendar')
		{
			$pjEBCalendar = new pjEBCalendar();
			
			$title_arr = array();
			$title_arr['avail_tickets'] = __('front_label_available_tickets', true);
			$title_arr['today'] = __('front_today', true);
			$pjEBCalendar
				->setPrevLink("&nbsp;")
				->setNextLink("&nbsp;")
				->setStartDay($this->option_arr['o_week_start'])
				->setWeekNumbers('left')
				->setDayNames(__('days_short', true))
				->setMonthNames(__('months', true))
				->setShowTooltip($this->option_arr['o_event_title_position'] == 'tooltip' ? true : false)
				->set('options', $this->option_arr)
				->set('dates', $event_date_arr)
				->set('titles', $title_arr);
			
			$this->set('calendar', $pjEBCalendar);
			
		}
		
		$this->set('event_arr', $event_arr);
		$this->set('event_date_arr', $event_date_arr);
	}
	
	public function pjActionLoadEventDetail()
	{
		$this->setAjax(true);
	
		$date = $_GET['date'];
		$start_ts = strtotime($date . ' 00:00:00');
		$end_ts = strtotime($date . ' 23:59:59');
		$pjEventModel = pjEventModel::factory();
	
		$pjEventModel->where("((t1.event_start_ts BETWEEN $start_ts AND $end_ts) OR (t1.event_end_ts BETWEEN $start_ts AND $end_ts) OR (t1.event_start_ts <= $start_ts AND t1.event_end_ts >= $end_ts))");
	
		if(isset($_GET['category_id']) && (int) $_GET['category_id'] > 0)
		{
			$pjEventModel->where('t1.category_id', $_GET['category_id']);
		}
	
		$event_arr = $pjEventModel
			->select("t1.*, t2.content as category, t3.content as title, t4.content as event_description, t5.content as event_location,
						(SELECT SUM(`TP`.available) FROM `".pjPriceModel::factory()->getTable()."` AS `TP` WHERE `TP`.event_id=t1.id) AS `total_avail`,
						(SELECT SUM(`TBD`.cnt) FROM `".pjBookingDetailModel::factory()->getTable()."` AS `TBD` WHERE `TBD`.booking_id IN (SELECT `TB`.id FROM `".pjBookingModel::factory()->getTable()."` as `TB` WHERE `TB`.event_id = t1.id AND (`TB`.booking_status ='confirmed' OR `TB`.booking_status ='pending' ))) AS `total_booked`")
			->join('pjMultiLang', "t2.foreign_id = t1.category_id AND t2.model = 'pjCategory' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
			->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjEvent' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'title'", 'left')
			->join('pjMultiLang', "t4.foreign_id = t1.id AND t4.model = 'pjEvent' AND t4.locale = '".$this->getLocaleId()."' AND t4.field = 'description'", 'left')
			->join('pjMultiLang', "t5.foreign_id = t1.id AND t5.model = 'pjEvent' AND t5.locale = '".$this->getLocaleId()."' AND t5.field = 'location'", 'left')
			->orderBy('t1.event_start_ts ASC')
			->findAll()
			->getData();
		$this->set('event_arr', $event_arr);
	}
	
	public function pjActionView()
	{
		$this->setAjax(true);
	
	
		$pjEventModel = pjEventModel::factory();
	
		$arr = $pjEventModel
			->select("t1.*, t6.content as category, t3.content as title, t4.content as event_description, t5.content as event_location,
					(SELECT SUM(`TP`.available) FROM `".pjPriceModel::factory()->getTable()."` AS `TP` WHERE `TP`.event_id=t1.id) AS `total_avail`,
					(SELECT SUM(`TBD`.cnt) FROM `".pjBookingDetailModel::factory()->getTable()."` AS `TBD` WHERE `TBD`.booking_id IN (SELECT `TB`.id FROM `".pjBookingModel::factory()->getTable()."` as `TB` WHERE `TB`.event_id = t1.id AND `TB`.booking_status ='confirmed')) AS `total_booked`")
			->join('pjCategory', 't2.id=t1.category_id', 'left outer')
			->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjEvent' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'title'", 'left')
			->join('pjMultiLang', "t4.foreign_id = t1.id AND t4.model = 'pjEvent' AND t4.locale = '".$this->getLocaleId()."' AND t4.field = 'description'", 'left')
			->join('pjMultiLang', "t5.foreign_id = t1.id AND t5.model = 'pjEvent' AND t5.locale = '".$this->getLocaleId()."' AND t5.field = 'location'", 'left')
			->join('pjMultiLang', "t6.foreign_id = t1.category_id AND t6.model = 'pjCategory' AND t6.locale = '".$this->getLocaleId()."' AND t6.field = 'name'", 'left')
			->find($_GET['id'])
			->getData();
	
		$price_arr = pjPriceModel::factory()
		->select("t1.*, t2.content as price_name, (SELECT SUM(cnt) FROM `" .pjBookingDetailModel::factory()->getTable(). "` as `TBD` WHERE `TBD`.price_id = t1.id AND `TBD`.booking_id IN(SELECT `TB`.id FROM `".pjBookingModel::factory()->getTable()."` as `TB` WHERE `TB`.booking_status='confirmed')) as cnt_booked")
		->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjPrice' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
		->where('event_id', $_GET['id'])
		->findAll()
		->getData();
			
		$this->set('arr', $arr);
		$this->set('price_arr', $price_arr);
	}
	
	public function pjActionLoadBookingForm()
	{
		$this->setAjax(true);
	
		$event_id = $_GET['event_id'];
	
		$arr = pjEventModel::factory()
			->select("t1.*, t2.content as category, t3.content as title, t4.content as event_description, t5.content as event_location, t6.content as booking_terms")
			->join('pjMultiLang', "t2.foreign_id = t1.category_id AND t2.model = 'pjEvent' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
			->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjEvent' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'title'", 'left')
			->join('pjMultiLang', "t4.foreign_id = t1.id AND t4.model = 'pjEvent' AND t4.locale = '".$this->getLocaleId()."' AND t4.field = 'description'", 'left')
			->join('pjMultiLang', "t5.foreign_id = t1.id AND t5.model = 'pjEvent' AND t5.locale = '".$this->getLocaleId()."' AND t5.field = 'location'", 'left')
			->join('pjMultiLang', "t6.foreign_id = t1.id AND t6.model = 'pjEvent' AND t6.locale = '".$this->getLocaleId()."' AND t6.field = 'terms'", 'left')
			->find($event_id)
			->getData();
	
		$price_arr = pjPriceModel::factory()
			->select("t1.*, t2.content as price_name,
					(SELECT SUM(cnt) FROM `" .pjBookingDetailModel::factory()->getTable(). "` as `TBD` WHERE `TBD`.price_id = t1.id AND `TBD`.booking_id IN(SELECT `TB`.id FROM `".pjBookingModel::factory()->getTable()."` as `TB` WHERE `TB`.booking_status='confirmed' OR `TB`.booking_status='pending')) as cnt_booked")
			->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjPrice' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
			->where('event_id', $event_id)
			->findAll()
			->getData();
	
		$country_arr = pjCountryModel::factory()
			->select('t1.id, t2.content AS country_title')
			->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
			->where('t1.status', 'T')
			->orderBy('`country_title` ASC')
			->findAll()
			->getData();
	
		$this->set('arr', $arr);
		$this->set('price_arr', $price_arr);
		$this->set('country_arr', $country_arr);
	}
	
	public function pjActionLoadBookingSummary()
	{
		$this->setAjax(true);
	
		$event_id = $_GET['event_id'];
	
		$amount_arr = $this->calcPrice($_POST['total_price'], $this->option_arr);
	
		$arr = pjEventModel::factory()
			->select("t1.*, t2.content as category, t3.content as title, t4.content as event_description, t5.content as event_location")
			->join('pjMultiLang', "t2.foreign_id = t1.category_id AND t2.model = 'pjEvent' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
			->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjEvent' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'title'", 'left')
			->join('pjMultiLang', "t4.foreign_id = t1.id AND t4.model = 'pjEvent' AND t4.locale = '".$this->getLocaleId()."' AND t4.field = 'description'", 'left')
			->join('pjMultiLang', "t5.foreign_id = t1.id AND t5.model = 'pjEvent' AND t5.locale = '".$this->getLocaleId()."' AND t5.field = 'location'", 'left')
			->find($event_id)
			->getData();
	
		$country_arr = pjCountryModel::factory()
			->select('t1.id, t2.content AS country_title')
			->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
			->where('t1.status', 'T')
			->orderBy('`country_title` ASC')
			->findAll()
			->getData();
	
		$price_arr = pjPriceModel::factory()
			->select("t1.*, t2.content as price_name,
					(SELECT SUM(cnt) FROM `" .pjBookingDetailModel::factory()->getTable(). "` as `TBD` WHERE `TBD`.price_id = t1.id AND `TBD`.booking_id IN(SELECT `TB`.id FROM `".pjBookingModel::factory()->getTable()."` as `TB` WHERE `TB`.booking_status='confirmed' OR `TB`.booking_status='pending')) as cnt_booked")
			->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjPrice' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
			->where('event_id', $event_id)
			->findAll()
			->getData();
	
		$this->set('arr', $arr);
		$this->set('price_arr', $price_arr);
		$this->set('amount', $amount_arr);
		$this->set('country_arr', $country_arr);
	}
	
	public function pjActionGetPaymentForm()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjBookingModel = pjBookingModel::factory();
				
			$booking_arr = $pjBookingModel
				->reset()
				->select('t1.*, t2.content as event_title')
				->join('pjMultiLang', "t2.foreign_id = t1.event_id AND t2.model = 'pjEvent' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'title'", 'left')
				->find($_GET['id'])->getData();
				
			switch ($booking_arr['payment_method'])
			{
				case 'paypal':
					$this->set('params', array(
					'name' => 'pjEbcPaypalForm',
					'id' => 'pjEbcPaypalForm',
					'business' => $this->option_arr['o_paypal_address'],
					'item_name' => $booking_arr['event_title'],
					'custom' => $booking_arr['id'],
					'amount' => $booking_arr['booking_deposit'],
					'currency_code' => $this->option_arr['o_currency'],
					'return' => $this->option_arr['o_thankyou_page'],
					'notify_url' => PJ_INSTALL_URL . 'index.php?controller=pjFrontEnd&action=pjActionConfirmPaypal',
					'target' => '_self',
					'charset' => 'utf-8'
							));
							break;
				case 'authorize':
					$this->set('params', array(
					'name' => 'pjEbcAuthorizeForm',
					'id' => 'pjEbcAuthorizeForm',
					'timezone' => $this->option_arr['o_authorize_timezone'],
					'transkey' => $this->option_arr['o_authorize_transkey'],
					'x_login' => $this->option_arr['o_authorize_merchant_id'],
					'x_description' => $booking_arr['event_title'],
					'x_amount' => $booking_arr['booking_deposit'],
					'x_invoice_num' => $booking_arr['id'],
					'x_relay_url' => PJ_INSTALL_URL . 'index.php?controller=pjFrontEnd&action=pjActionConfirmAuthorize'
							));
							break;
			}
				
			$this->set('booking_arr', $booking_arr);
			$this->log('submit payment form');
		}
	}
	public function pjActionCancel() {
		if (isset ( $_POST ['booking_cancel'] )) {
			$subject = __ ( 'emailCancelSubject', true );
			$message = __ ( 'emailCancelBody', true );
			
			if (! empty ( $subject ) && ! empty ( $message )) {
				$pjBookingModel = pjBookingModel::factory ();
				$pjBookingModel->setAttributes ( array (
						'id' => $_POST ['id'] 
				) )->modify ( array (
						'booking_status' => 'cancelled' 
				) );
				$arr = $pjBookingModel->reset ()->find ( $_POST ['id'] )->getData ();
				$search = array (
						'{BookingID}' 
				);
				$replace = array (
						$arr ['unique_id'] 
				);
				
				$pjEmail = new pjEmail ();
				
				if ($this->option_arr ['o_send_email'] == 'smtp') {
					$pjEmail
						->setTransport('smtp')
						->setSmtpHost($this->option_arr['o_smtp_host'])
						->setSmtpPort($this->option_arr['o_smtp_port'])
						->setSmtpUser($this->option_arr['o_smtp_user'])
						->setSmtpPass($this->option_arr['o_smtp_pass'])
						->setSender($this->option_arr['o_smtp_user']);
				}
				$from = $this->getFromEmail ();
				$pjEmail->setContentType ( 'text/plain' );
				$pjEmail->setFrom ( $from );
				
				$message = str_replace ( $search, $replace, $message );
				
				$pjEmail->setSubject ( $subject );
				
				$to = $from;
				$pjEmail->setTo ( $to );
				$pjEmail->send ( $message );
			}
			pjUtil::redirect ( $this->option_arr ['o_cancel_booking_page'] );
		} else {
			if (isset ( $_GET ['hash'] ) && isset ( $_GET ['id'] )) {
				$id = $_GET ['id'];
				$hash = $_GET ['hash'];
				
				$arr = pjBookingModel::factory ()->select ( 't1.*, t8.content as event_title, t9.content as description, t2.event_start_ts, t2.event_end_ts, , t2.o_show_start_time,
							t2.o_show_end_time, t3.content as country_title, t4.content as o_email_confirmation_subject, t5.content as o_email_confirmation,
							t6.content as o_email_payment_subject, t7.content as o_email_payment,
							t10.content as o_sms_confirmation, t11.content as o_sms_payment' )->join ( 'pjEvent', 't1.event_id = t2.id', 'left' )->join ( 'pjMultiLang', "t3.foreign_id = t1.customer_country AND t3.model = 'pjCountry' AND t3.locale = '" . $this->getLocaleId () . "' AND t3.field = 'name'", 'left' )->join ( 'pjMultiLang', "t4.foreign_id = t1.event_id AND t4.model = 'pjEvent' AND t4.locale = '" . $this->getLocaleId () . "' AND t4.field = 'o_email_confirmation_subject'", 'left' )->join ( 'pjMultiLang', "t5.foreign_id = t1.event_id AND t5.model = 'pjEvent' AND t5.locale = '" . $this->getLocaleId () . "' AND t5.field = 'o_email_confirmation'", 'left' )->join ( 'pjMultiLang', "t6.foreign_id = t1.event_id AND t6.model = 'pjEvent' AND t6.locale = '" . $this->getLocaleId () . "' AND t6.field = 'o_email_payment_subject'", 'left' )->join ( 'pjMultiLang', "t7.foreign_id = t1.event_id AND t7.model = 'pjEvent' AND t7.locale = '" . $this->getLocaleId () . "' AND t7.field = 'o_email_payment'", 'left' )->join ( 'pjMultiLang', "t8.foreign_id = t1.event_id AND t8.model = 'pjEvent' AND t8.locale = '" . $this->getLocaleId () . "' AND t8.field = 'title'", 'left' )->join ( 'pjMultiLang', "t9.foreign_id = t1.event_id AND t9.model = 'pjEvent' AND t9.locale = '" . $this->getLocaleId () . "' AND t9.field = 'description'", 'left' )->join ( 'pjMultiLang', "t10.foreign_id = t1.event_id AND t10.model = 'pjEvent' AND t10.locale = '" . $this->getLocaleId () . "' AND t10.field = 'o_sms_confirmation'", 'left' )->join ( 'pjMultiLang', "t11.foreign_id = t1.event_id AND t11.model = 'pjEvent' AND t11.locale = '" . $this->getLocaleId () . "' AND t11.field = 'o_sms_payment'", 'left' )->find ( $id )->getData ();
				if (count ( $arr ) > 0) {
					if ($arr ['booking_status'] == 'cancelled') {
						$this->set ( 'status', 4 );
					} else {
						if ($hash == md5 ( $arr ['id'] . $arr ['created'] . PJ_SALT )) {
							$this->set ( 'arr', $arr );
						} else {
							$this->set ( 'status', 3 );
						}
					}
				} else {
					$this->set ( 'status', 2 );
				}
			} elseif (! isset ( $_GET ['err'] )) {
				$this->set ( 'status', 1 );
			}
		}
		
		$this->appendCss ( 'front_cancel.css' );
	}
	
}
?>