<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminEvents extends pjAdmin
{
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['event_create']))
			{
				$pjEventModel = pjEventModel::factory();
				$data = array();
				$data['start_date'] = pjUtil::formatDate($_POST['start_date'], $this->option_arr['o_date_format']);
				$id = pjEventModel::factory()->setAttributes(array_merge($_POST, $data))->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$pjMultiLangModel = pjMultiLangModel::factory();
						
					if (isset($_POST['i18n']))
					{
						$pjMultiLangModel->saveMultiLang($_POST['i18n'], $id, 'pjEvent', 'data');
					}
					$err = 'AE03';
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminEvents&action=pjActionUpdate&event_id=$id&err=$err");
				} else {
					$err = 'AE04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminEvents&action=pjActionIndex&err=$err");
			} else {
				
				$locale_arr = pjLocaleModel::factory()
					->select('t1.*, t2.file')
					->join('pjLocaleLanguage', 't2.iso=t1.language_iso', 'left')
					->where('t2.file IS NOT NULL')
					->orderBy('t1.sort ASC')->findAll()->getData();
				
				$lp_arr = array();
				foreach ($locale_arr as $item)
				{
					$lp_arr[$item['id']."_"] = $item['file'];
				}
				$this->set('lp_arr', $locale_arr);
				$this->set('locale_str', pjAppController::jsonEncode($lp_arr));
				
				$this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
				$this->appendJs('jquery.tipsy.js', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendCss('jquery.tipsy.css', PJ_THIRD_PARTY_PATH . 'tipsy/');
				
				$this->appendJs('jquery.validate.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminEvents.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteEvent()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			
			$pjEventModel = pjEventModel::factory();
			$pjSeatModel = pjSeatModel::factory();
			$pjBookingModel = pjBookingModel::factory();
			$pjCodeModel = pjCodeModel::factory();
			$arr = $pjEventModel->find($_GET['id'])->getData();
			if ($pjEventModel->reset()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				if(!empty($arr['map']))
				{
					if (is_file(PJ_INSTALL_PATH . $arr['map']))
					{
						@unlink(PJ_INSTALL_PATH . $arr['map']);
					}
				}
				if(!empty($arr['ticket_img']))
				{
					if (is_file(PJ_INSTALL_PATH . $arr['ticket_img']))
					{
						@unlink(PJ_INSTALL_PATH . $arr['ticket_img']);
					}
				}
				$seat_id_arr = $pjSeatModel->where('event_id', $_GET['id'])->findAll()->getDataPair(null, 'id');
				if(!empty($seat_id_arr))
				{
					pjSeatTicketModel::factory()->whereIn('seat_id', $seat_id_arr)->eraseAll();
					$pjSeatModel->reset()->where('event_id', $_GET['id'])->eraseAll();
				}
				$booking_id_arr = $pjBookingModel->where('event_id', $_GET['id'])->findAll()->getDataPair(null, 'id');
				if(!empty($booking_id_arr))
				{
					$pjBookingModel->reset()->where('event_id', $_GET['id'])->eraseAll();
					pjBookingPaymentModel::factory()->whereIn('booking_id', $booking_id_arr)->eraseAll();					
					pjBookingTicketModel::factory()->whereIn('booking_id', $booking_id_arr)->eraseAll();
				}
				$code_id_arr = $pjCodeModel->where('event_id', $_GET['id'])->findAll()->getDataPair(null, 'id');
				if(!empty($code_id_arr))
				{
					pjCodeTicketModel::factory()->whereIn('code_id', $code_id_arr)->eraseAll();
					$pjCodeModel->reset()->where('event_id', $_GET['id'])->eraseAll();
				}
				pjMultiLangModel::factory()->where('model', 'pjEvent')->where('foreign_id', $_GET['id'])->eraseAll();
				pjWaitlistModel::factory()->where('event_id', $_GET['id'])->eraseAll();
				pjTicketModel::factory()->where('event_id', $_GET['id'])->eraseAll();
				
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteEventBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjEventModel = pjEventModel::factory();
			$pjSeatModel = pjSeatModel::factory();
			$pjBookingModel = pjBookingModel::factory();
			$pjCodeModel = pjCodeModel::factory();
				
			$arr = $pjEventModel->whereIn('id', $_POST['record'])->findAll()->getData();
			if(!empty($arr))
			{
				foreach($arr as $v)
				{
					if(!empty($v['map']))
					{
						if (is_file(PJ_INSTALL_PATH . $v['map']))
						{
							@unlink(PJ_INSTALL_PATH . $v['map']);
						}
					}
					if(!empty($v['ticket_img']))
					{
						if (is_file(PJ_INSTALL_PATH . $v['ticket_img']))
						{
							@unlink(PJ_INSTALL_PATH . $v['ticket_img']);
						}
					}
				}
				
				$seat_id_arr = $pjSeatModel->whereIn('event_id', $_POST['record'])->findAll()->getDataPair(null, 'id');
				if(!empty($seat_id_arr))
				{
					pjSeatTicketModel::factory()->whereIn('seat_id', $seat_id_arr)->eraseAll();
					$pjSeatModel->reset()->whereIn('event_id', $_POST['record'])->eraseAll();
				}
				$booking_id_arr = $pjBookingModel->whereIn('event_id', $_POST['record'])->findAll()->getDataPair(null, 'id');
				if(!empty($booking_id_arr))
				{
					$pjBookingModel->reset()->whereIn('event_id', $_POST['record'])->eraseAll();
					pjBookingPaymentModel::factory()->whereIn('booking_id', $booking_id_arr)->eraseAll();
					pjBookingTicketModel::factory()->whereIn('booking_id', $booking_id_arr)->eraseAll();
				}
				$code_id_arr = $pjCodeModel->whereIn('event_id', $_POST['record'])->findAll()->getDataPair(null, 'id');
				if(!empty($code_id_arr))
				{
					pjCodeTicketModel::factory()->whereIn('code_id', $code_id_arr)->eraseAll();
					$pjCodeModel->reset()->whereIn('event_id', $_POST['record'])->eraseAll();
				}
				pjMultiLangModel::factory()->where('model', 'pjEvent')->whereIn('foreign_id', $_POST['record'])->eraseAll();
				pjWaitlistModel::factory()->whereIn('event_id', $_POST['record'])->eraseAll();
				pjTicketModel::factory()->whereIn('event_id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionExportEvent()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjEventModel::factory()->whereIn('id', $_POST['record'])->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Events-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionGetEvent()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjEventModel = pjEventModel::factory()->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjEvent' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'title'", 'left');
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				
				$pjEventModel->where('t2.content LIKE', "%$q%");
			}
			
			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('T', 'F')))
			{
				$pjEventModel->where('t1.status', $_GET['status']);
			}
				
			$column = 'title';
			$direction = 'ASC';
			$allowed_columns = array('title', 'tickets_sold', 'available_tickets', 'cnt_subscribers', 'start_date', 'status');
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array($_GET['column'], $allowed_columns) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}
			
			$total = $pjEventModel->findCount()->getData();
			$rowCount = isset($_GET['rowCount']) && (int) $_GET['rowCount'] > 0 ? (int) $_GET['rowCount'] : 10;
			$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;
			}

			$data = $pjEventModel
				->select(sprintf("t1.*, 
								t2.content as title, 
								(SELECT COUNT(`TBT`.ticket_id) FROM `%1\$s` AS `TBT` WHERE `TBT`.booking_id IN (SELECT `TB`.id FROM `%2\$s` AS `TB` WHERE `TB`.event_id=t1.id AND `TB`.status='confirmed') ) AS tickets_sold,
							 	(SELECT COUNT(`TT`.id) FROM `%3\$s` AS `TT` WHERE `TT`.event_id=t1.id AND `TT`.`tickets_sold`='join') AS cnt_waitlists,
								(SELECT COUNT(`TW`.email) FROM `%4\$s` AS `TW` WHERE `TW`.event_id=t1.id) AS cnt_subscribers,
								(SELECT SUM(`TT2`.available_tickets) FROM `%3\$s` AS `TT2` WHERE `TT2`.event_id=t1.id) AS cnt_tickets,
								(SELECT MIN(`TT3`.sale_start) FROM `%3\$s` AS `TT3` WHERE `TT3`.event_id=t1.id) AS sale_starts,
								(SELECT MAX(`TT4`.sale_end) FROM `%3\$s` AS `TT4` WHERE `TT4`.event_id=t1.id) AS sale_ends
							",pjBookingTicketModel::factory()->getTable(), 
							pjBookingModel::factory()->getTable(),
							pjTicketModel::factory()->getTable(),
							pjWaitlistModel::factory()->getTable()
						))
				->orderBy("$column $direction")
				->limit($rowCount, $offset)->findAll()->getData();
			
			foreach($data as $k => $v)
			{
				$v['tickets_sold'] = (int) $v['tickets_sold'];
				$v['available_tickets'] = (int) $v['cnt_tickets'] - (int) $v['tickets_sold'];
				$v['cnt_subscribers'] = (int) $v['cnt_waitlists'] > 0 ? (int) $v['cnt_subscribers'] : __('lblNA', true);
				$v['start_date'] = !empty($v['start_date']) ? date($this->option_arr['o_date_format'], strtotime($v['start_date'])) : '';
				
				$data[$k] = $v;
			}
			
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminEvents.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveEvent()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjEventModel = pjEventModel::factory();
			if (!in_array($_POST['column'], $pjEventModel->i18n))
			{
				$value = $_POST['value'];
			
				$pjEventModel->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $value));
			} else {
				pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($_POST['column'] => $_POST['value'])), $_GET['id'], 'pjEvent', 'data');
			}
		}
		exit;
	}
	
	public function pjActionStatusEvent()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjEventModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array(
					'status' => ":IF(`status`='F','T','F')"
				));
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
				
			if (isset($_POST['event_update']))
			{
				$pjEventModel = pjEventModel::factory();
				
				$err = 'AE01';
				
				$arr = $pjEventModel->find($_POST['id'])->getData();
				if (empty($arr))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminEvents&action=pjActionIndex&err=AE08");
				}
				$data = array();
				$data['start_date'] = pjUtil::formatDate($_POST['start_date'], $this->option_arr['o_date_format']);
				$pjEventModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll(array_merge($_POST, $data));
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjEvent', 'data');
				}
				
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionUpdate&event_id=".$_POST['id']."&err=AE01");
				
			} else {
				$pjEventModel = pjEventModel::factory();
				$pjMultiLangModel = pjMultiLangModel::factory();

				$arr = $pjEventModel
					->select(sprintf("t1.*, 
								(SELECT COUNT(`TBT`.ticket_id) FROM `%1\$s` AS `TBT` WHERE `TBT`.booking_id IN (SELECT `TB`.id FROM `%2\$s` AS `TB` WHERE `TB`.event_id=t1.id AND `TB`.status='confirmed') ) AS tickets_sold,
							 	(SELECT COUNT(`TT`.id) FROM `%3\$s` AS `TT` WHERE `TT`.event_id=t1.id AND `TT`.`tickets_sold`='join') AS cnt_waitlists,
								(SELECT COUNT(`TW`.email) FROM `%4\$s` AS `TW` WHERE `TW`.event_id=t1.id) AS cnt_subscribers,
								(SELECT SUM(`TT2`.available_tickets) FROM `%3\$s` AS `TT2` WHERE `TT2`.event_id=t1.id) AS cnt_tickets,
								(SELECT COUNT(`TT3`.id) FROM `%3\$s` AS `TT3` WHERE `TT3`.event_id=t1.id) AS total_tickets
							",pjBookingTicketModel::factory()->getTable(), 
							pjBookingModel::factory()->getTable(),
							pjTicketModel::factory()->getTable(),
							pjWaitlistModel::factory()->getTable()
						))
					->find($_GET['event_id'])
					->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminEvents&action=pjActionIndex&err=AE08");
				}
				$arr['i18n'] = $pjMultiLangModel->getMultiLang($arr['id'], 'pjEvent');
								
							
				$this->set('event_arr', $arr);
				
				$locale_arr = pjLocaleModel::factory()
					->select('t1.*, t2.file')
					->join('pjLocaleLanguage', 't2.iso=t1.language_iso', 'left')
					->where('t2.file IS NOT NULL')
					->orderBy('t1.sort ASC')->findAll()->getData();
				
				$lp_arr = array();
				foreach ($locale_arr as $item)
				{
					$lp_arr[$item['id']."_"] = $item['file'];
				}
				$this->set('lp_arr', $locale_arr);
				$this->set('locale_str', pjAppController::jsonEncode($lp_arr));
				
				$this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
				$this->appendJs('jquery.tipsy.js', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendCss('jquery.tipsy.css', PJ_THIRD_PARTY_PATH . 'tipsy/');
				
				$this->appendJs('jquery.validate.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminEvents.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionTickets()
	{
		$this->checkLogin();
	
		if ($this->isAdmin() || $this->isEditor())
		{
	
			if (isset($_POST['ticket_update']))
			{
				$pjTicketModel = pjTicketModel::factory();
	
				$data = array();
				
				$start_arr = pjUtil::convertDateTime($_POST['sale_start'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
				$end_arr = pjUtil::convertDateTime($_POST['sale_end'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
				
				$data['sale_start'] = $start_arr['iso_date_time'];
				$data['sale_end'] = $end_arr['iso_date_time'];
				
				if($_POST['type'] != 'paid')
				{
					$data['price'] = ':NULL';
				}
				if(isset($_POST['show_sale_start']))
				{
					$data['show_sale_start'] = 'F';
				}else{
					$data['show_sale_start'] = 'T';
				}
				if(isset($_POST['show_sale_end']))
				{
					$data['show_sale_end'] = 'F';
				}else{
					$data['show_sale_end'] = 'T';
				}
				
				if(!isset($_POST['id']))
				{
					$id = $pjTicketModel->setAttributes(array_merge($_POST, $data))->insert()->getInsertId();
					if ($id !== false && (int) $id > 0)
					{
						$pjMultiLangModel = pjMultiLangModel::factory();
					
						if (isset($_POST['i18n']))
						{
							$pjMultiLangModel->saveMultiLang($_POST['i18n'], $id, 'pjTicket', 'data');
						}
						pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionTickets&event_id=".$_POST['event_id'] . "&err=AT03");
					} else {
						pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionTickets&event_id=".$_POST['event_id'] . "&err=AT04");
					}
				}else{
					$arr = $pjTicketModel->find($_POST['id'])->getData();
					if (count($arr) === 0)
					{
						pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionTickets&event_id=".$_POST['event_id'] . "&err=AT08");
					}
					$pjTicketModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll(array_merge($_POST, $data));
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjTicket', 'data');
					}
					pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionTickets&event_id=".$_POST['event_id'] . "&err=AT01");
				}
			} else {
				$pjMultiLangModel = pjMultiLangModel::factory();
	
				$event_arr = pjEventModel::factory()
					->select("t1.*, t2.content as title, (SELECT COUNT(`TT`.id) FROM `".pjTicketModel::factory()->getTable()."` AS `TT` WHERE `TT`.event_id=t1.id AND `TT`.`tickets_sold`='join') AS cnt_waitlists")
					->join('pjMultiLang', "t2.model='pjEvent' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->find($_GET['event_id'])->getData();
				$this->set('event_arr', $event_arr);
				
				if(isset($_GET['id']))
				{
					$arr = pjTicketModel::factory()->find($_GET['id'])->getData();
					$arr['i18n'] = $pjMultiLangModel->getMultiLang($arr['id'], 'pjTicket');
					$this->set('arr', $arr);
				}
				
				$locale_arr = pjLocaleModel::factory()
					->select('t1.*, t2.file')
					->join('pjLocaleLanguage', 't2.iso=t1.language_iso', 'left')
					->where('t2.file IS NOT NULL')
					->orderBy('t1.sort ASC')->findAll()->getData();
	
				$lp_arr = array();
				foreach ($locale_arr as $item)
				{
					$lp_arr[$item['id']."_"] = $item['file'];
				}
				$this->set('lp_arr', $locale_arr);
				$this->set('locale_str', pjAppController::jsonEncode($lp_arr));
	
				$this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
				$this->appendJs('jquery.tipsy.js', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendCss('jquery.tipsy.css', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendJs('jquery-ui-timepicker-addon.js', PJ_THIRD_PARTY_PATH . 'datetimepicker/');
				$this->appendCss('jquery-ui-timepicker-addon.css', PJ_THIRD_PARTY_PATH . 'datetimepicker/');
				$this->appendJs('jquery.validate.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('additional-methods.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
				$this->appendJs('pjAdminEvents.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetTicket()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjTicketModel = pjTicketModel::factory()
				->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjTicket' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'title'", 'left');
			if (isset($_GET['event_id']) && (int) $_GET['event_id'] > 0)
			{
				$pjTicketModel->where('event_id', $_GET['event_id']);
			}	
			$column = 'title';
			$direction = 'ASC';
			$allowed_columns = array('title', 'available_tickets', 'sold_tickets', 'price');
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array($_GET['column'], $allowed_columns) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}
				
			$total = $pjTicketModel->findCount()->getData();
			$rowCount = isset($_GET['rowCount']) && (int) $_GET['rowCount'] > 0 ? (int) $_GET['rowCount'] : 10;
			$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;
			}
	
			$data = $pjTicketModel
				->select("t1.*, t2.content as title, (SELECT COUNT(`TBT`.ticket_id) FROM `".pjBookingTicketModel::factory()->getTable()."` AS `TBT` WHERE `TBT`.ticket_id=t1.id AND `TBT`.booking_id IN (SELECT `TB`.id FROM `".pjBookingModel::factory()->getTable()."` AS `TB` WHERE `TB`.event_id=t1.event_id AND `TB`.status='confirmed' )) AS sold_tickets")
				->orderBy("$column $direction")
				->limit($rowCount, $offset)->findAll()->getData();
			foreach($data as $k => $v)
			{
				switch ($v['type']) {
					case 'paid':
						$v['price'] = pjUtil::formatCurrencySign($v['price'], $this->option_arr['o_currency']);	
					break;
					case 'free':
						$v['price'] = __('lblFree', true);	
					break;
					case 'donation':
						$v['price'] = __('lblDonation', true);
					break;
				}
				$data[$k] = $v;
			}	
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionDeleteTicket()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			
			if (pjTicketModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				pjSeatTicketModel::factory()->where('ticket_id', $_GET['id'])->eraseAll();
				pjBookingTicketModel::factory()->where('ticket_id', $_GET['id'])->eraseAll();
				pjCodeTicketModel::factory()->where('ticket_id', $_GET['id'])->eraseAll();
				pjWaitlistModel::factory()->where('ticket_id', $_GET['id'])->eraseAll();
				
				pjMultiLangModel::factory()->where('model', 'pjTicket')->where('foreign_id', $_GET['id'])->eraseAll();
				
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteTicketBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			pjTicketModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
			pjSeatTicketModel::factory()->whereIn('ticket_id', $_POST['record'])->eraseAll();
			pjBookingTicketModel::factory()->whereIn('ticket_id', $_POST['record'])->eraseAll();
			pjCodeTicketModel::factory()->whereIn('ticket_id', $_POST['record'])->eraseAll();
			pjWaitlistModel::factory()->whereIn('ticket_id', $_POST['record'])->eraseAll();
			pjMultiLangModel::factory()->where('model', 'pjTicket')->whereIn('foreign_id', $_POST['record'])->eraseAll();
		}
		exit;
	}
	
	public function pjActionDiscount()
	{
		$this->checkLogin();
	
		if ($this->isAdmin() || $this->isEditor())
		{
	
			if (isset($_POST['discount_update']))
			{
				$pjCodeModel = pjCodeModel::factory();
				$pjCodeTicketModel = pjCodeTicketModel::factory();
				
				$data = array();
				
				$from_arr = pjUtil::convertDateTime($_POST['valid_from'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
				$to_arr = pjUtil::convertDateTime($_POST['valid_to'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
				
				$data['valid_from'] = $from_arr['iso_date_time'];
				$data['valid_to'] = $to_arr['iso_date_time'];
				
				if(!isset($_POST['id']))
				{
					$id = $pjCodeModel->setAttributes(array_merge($_POST, $data))->insert()->getInsertId();
					if ($id !== false && (int) $id > 0)
					{
						if(isset($_POST['ticket_id']) && count($_POST['ticket_id']) > 0)
						{
							$pjCodeTicketModel->begin();
							foreach ($_POST['ticket_id'] as $ticket_id)
							{
								$pjCodeTicketModel
									->reset()
									->set('code_id', $id)
									->set('ticket_id', $ticket_id)
									->insert();
							}
							$pjCodeTicketModel->commit();
						}
						pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionDiscount&event_id=".$_POST['event_id'] . "&err=AC03");
					} else {
						pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionDiscount&event_id=".$_POST['event_id'] . "&err=AC04");
					}
				}else{
					$arr = $pjCodeModel->find($_POST['id'])->getData();
					if (count($arr) === 0)
					{
						pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionTickets&event_id=".$_POST['event_id'] . "&err=AC08");
					}
					$pjCodeModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll(array_merge($_POST, $data));
					
					$pjCodeTicketModel->where('code_id', $_POST['id'])->eraseAll();
					if (isset($_POST['ticket_id']) && is_array($_POST['ticket_id']) && count($_POST['ticket_id']) > 0)
					{
						$pjCodeTicketModel->reset()->begin();
						foreach ($_POST['ticket_id'] as $ticket_id)
						{
							$pjCodeTicketModel
								->reset()
								->set('code_id', $_POST['id'])
								->set('ticket_id', $ticket_id)
								->insert();
						}
						$pjCodeTicketModel->commit();
					}
					
					pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionDiscount&event_id=".$_POST['event_id'] . "&err=AC01");
				}
			} else {
				
				$event_arr = pjEventModel::factory()
					->select("t1.*, t2.content as title, (SELECT COUNT(`TT`.id) FROM `".pjTicketModel::factory()->getTable()."` AS `TT` WHERE `TT`.event_id=t1.id AND `TT`.`tickets_sold`='join') AS cnt_waitlists")
					->join('pjMultiLang', "t2.model='pjEvent' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->find($_GET['event_id'])->getData();
					
				$this->set('event_arr', $event_arr);
	
				if(isset($_GET['id']))
				{
					$this->set('arr', pjCodeModel::factory()->find($_GET['id'])->getData());
					$this->set('ticket_id_arr', pjCodeTicketModel::factory()->where("code_id", $_GET['id'])->findAll()->getDataPair(null, 'ticket_id'));
				}
	
				$ticket_arr = pjTicketModel::factory()
					->select('t1.*, t2.content as title')
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjTicket' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'title'", 'left')
					->where("t1.event_id", $_GET['event_id'])
					->orderBy("title ASC")
					->findAll()
					->getData();
				$this->set('ticket_arr', $ticket_arr);
				
				$this->appendJs('jquery-ui-timepicker-addon.js', PJ_THIRD_PARTY_PATH . 'datetimepicker/');
				$this->appendCss('jquery-ui-timepicker-addon.css', PJ_THIRD_PARTY_PATH . 'datetimepicker/');
				$this->appendJs('jquery.multiselect.min.js', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendCss('jquery.multiselect.css', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendJs('jquery.validate.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
				$this->appendJs('pjAdminEvents.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetDiscount()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjCodeModel = pjCodeModel::factory();
			if (isset($_GET['event_id']) && (int) $_GET['event_id'] > 0)
			{
				$pjCodeModel->where('event_id', $_GET['event_id']);
			}
			$column = 'code';
			$direction = 'ASC';
			$allowed_columns = array('code', 'discount', 'valid_from', 'valid_to');
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array($_GET['column'], $allowed_columns) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}
	
			$total = $pjCodeModel->findCount()->getData();
			$rowCount = isset($_GET['rowCount']) && (int) $_GET['rowCount'] > 0 ? (int) $_GET['rowCount'] : 10;
			$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;
			}
	
			$data = $pjCodeModel
				->orderBy("$column $direction")
				->limit($rowCount, $offset)->findAll()->getData();
			foreach($data as $k => $v)
			{
				$v['valid_from'] = date($this->option_arr['o_date_format'], strtotime($v['valid_from'])) . ', ' . date($this->option_arr['o_time_format'], strtotime($v['valid_from']));
				$v['valid_to'] = date($this->option_arr['o_date_format'], strtotime($v['valid_to'])) . ', ' . date($this->option_arr['o_time_format'], strtotime($v['valid_to']));
				$v['discount'] = $v['type'] == 'amount' ? pjUtil::formatCurrencySign($v['discount'], $this->option_arr['o_currency']) : $v['discount'] . '%';
				$data[$k] = $v;
			}
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	public function pjActionDeleteDiscount()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
				
			if (pjCodeModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				pjCodeTicketModel::factory()->where('code_id', $_GET['id'])->eraseAll();
				
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteDiscountBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			pjCodeModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
			pjCodeTicketModel::factory()->whereIn('code_id', $_POST['record'])->eraseAll();
		}
		exit;
	}
	
	public function pjActionMap()
	{
		$this->checkLogin();
	
		if ($this->isAdmin() || $this->isEditor())
		{
			$post_max_size = pjUtil::getPostMaxSize();
			if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && (int) $_SERVER['CONTENT_LENGTH'] > $post_max_size)
			{
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionMap&event_id=".$_GET['event_id']."&err=AM05");
			}
			if (isset($_POST['map_update']))
			{
				if (isset($_FILES['map']))
				{
					if($_FILES['map']['error'] == 0)
					{
						if(getimagesize($_FILES['map']["tmp_name"]) != false)
						{
							if (is_writable('app/web/upload/maps'))
							{
								$Image = new pjImage();
								if ($Image->getErrorCode() !== 200)
								{
									$Image->setAllowedTypes(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg'));
									if ($Image->load($_FILES['map']))
									{
										$resp = $Image->isConvertPossible();
										if ($resp['status'] === true)
										{
											$hash = md5(uniqid(rand(), true));
											$image_path = PJ_UPLOAD_PATH . 'maps/' . $_POST['event_id'] . '_' . $hash . '.' . $Image->getExtension();
												
											$Image->loadImage();
											$Image->saveImage($image_path);
											$data = array();
											$data['map'] = $image_path;
											
											pjEventModel::factory()->where('id', $_POST['event_id'])->limit(1)->modifyAll($data);
										}
									}
								}
							}else{
								pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionMap&event_id=".$_GET['event_id']."&err=AM11");
							}
						}else{
							pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionMap&event_id=".$_GET['event_id']."&err=AM12");
						}
					}else if($_FILES['map']['error'] != 4){
						pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionMap&event_id=".$_GET['event_id']."&err=AM09");
					}
				}
				
				$pjSeatModel = pjSeatModel::factory();
				$pjSeatTicketModel = pjSeatTicketModel::factory();
				if (isset($_POST['seats']))
				{
					$seat1_arr = array_values($pjSeatModel->where('event_id', $_POST['event_id'])->findAll()->getDataPair('id', 'id'));
					$seat2_arr = array();
					$sdata = array();
					foreach ($_POST['seats'] as $seat)
					{
						list($id, $sdata['width'], $sdata['height'], $sdata['left'], $sdata['top'], $sdata['name'], $sdata['seats'], $tmp, $ticket_id_str) = explode("|", $seat);
						$seat2_arr[] = $id;
						$sdata['event_id'] = $_POST['event_id'];
						$pjSeatModel->reset()->where('id', $id)->limit(1)->modifyAll($sdata);
						
						$ticket_id_arr = explode(",", $ticket_id_str);
						if(!empty($ticket_id_arr))
						{
							$pjSeatTicketModel->reset()->where('seat_id', $id)->eraseAll();
							foreach($ticket_id_arr as $ticket_id)
							{
								$seat_ticket_data = array();
								$seat_ticket_data['seat_id'] = $id;
								$seat_ticket_data['ticket_id'] = $ticket_id;
								$pjSeatTicketModel->reset()->setAttributes($seat_ticket_data)->insert();
							}
						}
					}
					$diff = array_diff($seat1_arr, $seat2_arr);
					if (count($diff) > 0)
					{
						$pjSeatModel->reset()->whereIn('id', $diff)->eraseAll();
					}
				}
				if (isset($_POST['seats_new']))
				{
					$sdata = array();
					foreach ($_POST['seats_new'] as $seat)
					{
						list(, $sdata['width'], $sdata['height'], $sdata['left'], $sdata['top'], $sdata['name'], $sdata['seats'], $tmp, $ticket_id_str) = explode("|", $seat);
						$sdata['event_id'] = $_POST['event_id'];
						$seat_id = $pjSeatModel->reset()->setAttributes($sdata)->insert()->getInsertId();
						if ($seat_id !== false && (int) $seat_id > 0)
						{
							$ticket_id_arr = explode(",", $ticket_id_str);
							if(!empty($ticket_id_arr))
							{
								foreach($ticket_id_arr as $ticket_id)
								{
									$seat_ticket_data = array();
									$seat_ticket_data['seat_id'] = $seat_id;
									$seat_ticket_data['ticket_id'] = $ticket_id;
									$pjSeatTicketModel->reset()->setAttributes($seat_ticket_data)->insert();
								}
							}
						}
					}
				}
				
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionMap&event_id=".$_GET['event_id']."&err=AM01");
			} else {
				$event_arr = pjEventModel::factory()
					->select("t1.*, t2.content as title, (SELECT COUNT(`TT`.id) FROM `".pjTicketModel::factory()->getTable()."` AS `TT` WHERE `TT`.event_id=t1.id AND `TT`.`tickets_sold`='join') AS cnt_waitlists")
					->join('pjMultiLang', "t2.model='pjEvent' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->find($_GET['event_id'])->getData();
				$this->set('event_arr', $event_arr);
	
				if(!empty($event_arr['map']))
				{
					$seat_arr = pjSeatModel::factory()->where('event_id', $_GET['event_id'])->orderBy("t1.id ASC")->findAll()->getData();
					$ticket_id_arr = array();
					$_ticket_id_arr = pjSeatTicketModel::factory()->where("(t1.seat_id IN (SELECT TS.id FROM `".pjSeatModel::factory()->getTable()."` AS `TS` WHERE TS.event_id=".$_GET['event_id'].") )")->findAll()->getData();
					foreach($_ticket_id_arr as $k => $v)
					{
						$ticket_id_arr[$v['seat_id']][] = $v['ticket_id'];
					}
					
					$this->set('seat_arr', $seat_arr);
					$this->set('ticket_id_arr', $ticket_id_arr);
				}
				
				$ticket_arr = pjTicketModel::factory()
					->select('t1.*, t2.content as title')
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjTicket' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'title'", 'left')
					->where("t1.event_id", $_GET['event_id'])
					->orderBy("title ASC")
					->findAll()
					->getData();
				$this->set('ticket_arr', $ticket_arr);
				
				$this->appendJs('jquery.multiselect.min.js', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendCss('jquery.multiselect.css', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendJs('jquery.validate.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
				$this->appendJs('pjAdminEvents.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteMap()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjEventModel = pjEventModel::factory();
			$pjSeatModel = pjSeatModel::factory();
			$arr = $pjEventModel->find($_POST['id'])->getData();
				
			if(!empty($arr))
			{
				$map_path = $arr['map'];
				if (file_exists(PJ_INSTALL_PATH . $map_path)) 
				{
					@unlink(PJ_INSTALL_PATH . $map_path);
				}
				$data = array();
				$data['map'] = ':NULL';
				$pjEventModel->reset()->where(array('id' => $_POST['id']))->limit(1)->modifyAll($data);
				$seat_id_arr = $pjSeatModel->where('event_id', $_POST['id'])->findAll()->getDataPair(null, 'id');
				if(!empty($seat_id_arr))
				{
					pjSeatTicketModel::factory()->whereIn('seat_id', $seat_id_arr)->eraseAll();
				}
				$pjSeatModel->reset()->where('event_id', $_POST['id'])->eraseAll();
	
				$this->set('code', 200);
			}else{
				$this->set('code', 100);
			}
		}
	}
	
	public function pjActionWaitlist()
	{
		$this->checkLogin();
	
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['waitlist_update']))
			{
				$pjWaitlistModel = pjWaitlistModel::factory();
				
				if(isset($_POST['id']))
				{
					$arr = $pjWaitlistModel->find($_POST['id'])->getData();
					if (count($arr) === 0)
					{
						pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionTickets&event_id=".$_POST['event_id'] . "&err=AW08");
					}
					$pjWaitlistModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll($_POST);
						
					pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionWaitlist&event_id=".$_POST['event_id'] . "&err=AW01");
				}
			} else {
				$event_arr = pjEventModel::factory()
					->select("t1.*, t2.content as title, (SELECT COUNT(`TT`.id) FROM `".pjTicketModel::factory()->getTable()."` AS `TT` WHERE `TT`.event_id=t1.id AND `TT`.`tickets_sold`='join') AS cnt_waitlists")
					->join('pjMultiLang', "t2.model='pjEvent' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->find($_GET['event_id'])->getData();
				if((int) $event_arr['cnt_waitlists'] <= 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionUpdate&event_id=".$_GET['event_id']);
				}
				$this->set('event_arr', $event_arr);
				
				if(isset($_GET['id']))
				{
					$this->set('arr', pjWaitlistModel::factory()->select("t1.*, t2.content as title")->join('pjMultiLang', "t2.foreign_id = t1.ticket_id AND t2.model = 'pjTicket' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'title'", 'left')->find($_GET['id'])->getData());
				}
				
				$this->appendJs('jquery.validate.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
				$this->appendJs('pjAdminEvents.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetWaitlist()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjWaitlistModel = pjWaitlistModel::factory()->join('pjMultiLang', "t2.foreign_id = t1.ticket_id AND t2.model = 'pjTicket' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'title'", 'left');
			if (isset($_GET['event_id']) && (int) $_GET['event_id'] > 0)
			{
				$pjWaitlistModel->where('event_id', $_GET['event_id']);
			}
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
			
				$pjWaitlistModel->where("(t2.content LIKE '%$q%' OR t1.name LIKE '%$q%' OR t1.email LIKE '%$q%')");
			}
			$column = 'created';
			$direction = 'DESC';
			$allowed_columns = array('title', 'name', 'email');
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array($_GET['column'], $allowed_columns) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}
	
			$total = $pjWaitlistModel->findCount()->getData();
			$rowCount = isset($_GET['rowCount']) && (int) $_GET['rowCount'] > 0 ? (int) $_GET['rowCount'] : 10;
			$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;
			}
	
			$data = $pjWaitlistModel
				->select("t1.*, t2.content as title")
				->orderBy("$column $direction")
				->limit($rowCount, $offset)->findAll()->getData();
			
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionDeleteWaitlist()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
	
			if (pjWaitlistModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteWaitlistBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			pjWaitlistModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
		}
		exit;
	}
	
	public function pjActionExportWaitlist()
	{
		$this->checkLogin();
	
		if(isset($_GET['event_id']) && (int) $_GET['event_id'] > 0)
		{
			$arr = pjWaitlistModel::factory()
				->select("t1.event_id, t2.content as ticket, t1.name, t1.email, t1.created")
				->join('pjMultiLang', "t2.foreign_id = t1.ticket_id AND t2.model = 'pjTicket' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'title'", 'left')
				->where('t1.event_id', $_GET['event_id'])
				->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Waitlist-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionPrintWaitlist()
	{
		$this->checkLogin();
	
		$this->setLayout('pjActionPrint');
		
		if ($this->isAdmin())
		{
			$event_arr = pjEventModel::factory()
				->select("t1.*, t2.content as title, (SELECT COUNT(`TT`.id) FROM `".pjTicketModel::factory()->getTable()."` AS `TT` WHERE `TT`.event_id=t1.id AND `TT`.`tickets_sold`='join') AS cnt_waitlists")
				->join('pjMultiLang', "t2.model='pjEvent' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->find($_GET['event_id'])
				->getData();
			if((int) $event_arr['cnt_waitlists'] <= 0)
			{
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionUpdate&event_id=".$_GET['event_id']);
			}
			
			$arr = pjWaitlistModel::factory()
				->select("t1.event_id, t2.content as ticket, t1.name, t1.email, t1.created")
				->join('pjMultiLang', "t2.foreign_id = t1.ticket_id AND t2.model = 'pjTicket' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'title'", 'left')
				->where('t1.event_id', $_GET['event_id'])
				->findAll()->getData();
			
			$this->set('arr', $arr);
			$this->set('event_arr', $event_arr);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionTicket()
	{
		$this->checkLogin();
	
		if ($this->isAdmin() || $this->isEditor())
		{
			$post_max_size = pjUtil::getPostMaxSize();
			if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && (int) $_SERVER['CONTENT_LENGTH'] > $post_max_size)
			{
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionTicket&event_id=".$_GET['event_id']."&err=AET05");
			}
			if (isset($_POST['i18n']))
			{
				pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['event_id'], 'pjEvent', 'data');
			}
			if (isset($_POST['ticket_update']))
			{
				if (isset($_FILES['ticket_img']))
				{
					if($_FILES['ticket_img']['error'] == 0)
					{
						if(getimagesize($_FILES['ticket_img']["tmp_name"]) != false)
						{
							if (is_writable('app/web/upload/tickets'))
							{
								$Image = new pjImage();
								if ($Image->getErrorCode() !== 200)
								{
									$Image->setAllowedTypes(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg'));
									if ($Image->load($_FILES['ticket_img']))
									{
										$resp = $Image->isConvertPossible();
										if ($resp['status'] === true)
										{
											$hash = md5(uniqid(rand(), true));
											$image_path = PJ_UPLOAD_PATH . 'tickets/' . $_POST['event_id'] . '_' . $hash . '.' . $Image->getExtension();
	
											$Image->loadImage();
											$Image->saveImage($image_path);
											$data = array();
											$data['ticket_img'] = $image_path;
												
											pjEventModel::factory()->where('id', $_POST['event_id'])->limit(1)->modifyAll($data);
										}
									}
								}
							}else{
								pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionMap&event_id=".$_GET['event_id']."&err=AET11");
							}
						}else{
							pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionMap&event_id=".$_GET['event_id']."&err=AET12");
						}
					}else if($_FILES['ticket_img']['error'] != 4){
						pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionMap&event_id=".$_GET['event_id']."&err=AET09");
					}
				}
	
				
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEvents&action=pjActionTicket&event_id=".$_GET['event_id']."&err=AET01");
			} else {
				$event_arr = pjEventModel::factory()
					->select("t1.*, t2.content as title, (SELECT COUNT(`TT`.id) FROM `".pjTicketModel::factory()->getTable()."` AS `TT` WHERE `TT`.event_id=t1.id AND `TT`.`tickets_sold`='join') AS cnt_waitlists")
					->join('pjMultiLang', "t2.model='pjEvent' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->find($_GET['event_id'])->getData();
				
				$event_arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($event_arr['id'], 'pjEvent');
				$this->set('event_arr', $event_arr);
	
				$locale_arr = pjLocaleModel::factory()
					->select('t1.*, t2.file')
					->join('pjLocaleLanguage', 't2.iso=t1.language_iso', 'left')
					->where('t2.file IS NOT NULL')
					->orderBy('t1.sort ASC')->findAll()->getData();
				
				$lp_arr = array();
				foreach ($locale_arr as $item)
				{
					$lp_arr[$item['id']."_"] = $item['file'];
				}
				$this->set('lp_arr', $locale_arr);
				$this->set('locale_str', pjAppController::jsonEncode($lp_arr));
				
				$this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
				$this->appendJs('jquery.tipsy.js', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendCss('jquery.tipsy.css', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendJs('jquery.validate.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
				$this->appendJs('pjAdminEvents.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteTicketImage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjEventModel = pjEventModel::factory();
			$arr = $pjEventModel->find($_GET['id'])->getData();
	
			if(!empty($arr))
			{
				$ticket_img_path = $arr['ticket_img'];
				if (file_exists(PJ_INSTALL_PATH . $ticket_img_path))
				{
					@unlink(PJ_INSTALL_PATH . $ticket_img_path);
				}
				$data = array();
				$data['ticket_img'] = ':NULL';
				$pjEventModel->reset()->where(array('id' => $_GET['id']))->limit(1)->modifyAll($data);
				
				$this->set('code', 200);
			}else{
				$this->set('code', 100);
			}
		}
	}
	
	public function pjActionPrintTickets()
	{
		$this->checkLogin();
	
		$this->setLayout('pjActionPrint');
	
		if ($this->isAdmin())
		{
			if(isset($_GET['event_id']) && (int) $_GET['event_id'] > 0)
			{
				$arr = pjBookingTicketModel::factory()
					->select("t1.*, t2.content as ticket, t3.created, t4.name as seat_name")
					->join('pjMultiLang', "t2.model='pjTicket' AND t2.foreign_id=t1.ticket_id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjBooking', "t3.id=t1.booking_id", "left outer")
					->join('pjSeat', "t4.id=t1.seat_id", "left outer")
					->where('t3.status', 'confirmed')
					->where('t3.event_id', $_GET['event_id'])
					->orderBy("attendee_name ASC")
					->findAll()
					->getData();
				
				$this->set('arr', $arr);
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionBookings()
	{
		$this->checkLogin();
	
		if ($this->isAdmin() || $this->isEditor())
		{
			$event_info_arr = $this->getEventBookings($_GET['event_id']);
			
			$this->set('event_arr', $event_info_arr['event_arr']);
			$this->set('booking_arr', $event_info_arr['booking_arr']);
			
			$this->appendJs('pjAdminEvents.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}
	public function pjActionPrintBookings()
	{
		$this->checkLogin();
	
		$this->setLayout('pjActionPrint');
	
		if ($this->isAdmin())
		{
			if(isset($_GET['event_id']) && (int) $_GET['event_id'] > 0)
			{
				$event_info_arr = $this->getEventBookings($_GET['event_id']);
			
				$this->set('event_arr', $event_info_arr['event_arr']);
				$this->set('booking_arr', $event_info_arr['booking_arr']);
			}
		} else {
			$this->set('status', 2);
		}
	}
	public function getEventBookings($event_id)
	{
		$pjEventModel = pjEventModel::factory();
			
		$event_arr = $pjEventModel
			->select(sprintf("t1.*, t2.content AS title,
								(SELECT COUNT(`TBT`.ticket_id) FROM `%1\$s` AS `TBT` WHERE `TBT`.booking_id IN (SELECT `TB`.id FROM `%2\$s` AS `TB` WHERE `TB`.event_id=t1.id AND `TB`.status='confirmed') ) AS tickets_sold,
								(SELECT COUNT(`TBT2`.ticket_id) FROM `%1\$s` AS `TBT2` WHERE `TBT2`.is_used='T' AND `TBT2`.booking_id IN (SELECT `TB2`.id FROM `%2\$s` AS `TB2` WHERE `TB2`.event_id=t1.id AND `TB2`.status='confirmed') ) AS tickets_used,
							 	(SELECT COUNT(`TB3`.id) FROM `%2\$s` AS `TB3` WHERE `TB3`.event_id=t1.id) AS total_bookings,
								(SELECT COUNT(`TT`.id) FROM `%3\$s` AS `TT` WHERE `TT`.event_id=t1.id AND `TT`.`tickets_sold`='join') AS cnt_waitlists
							",pjBookingTicketModel::factory()->getTable(),
							pjBookingModel::factory()->getTable(),
							pjTicketModel::factory()->getTable()
				))
			->join('pjMultiLang', "t2.model='pjEvent' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
			->find($event_id)
			->getData();
		if(pjSeatModel::factory()->where('t1.event_id', $event_id)->findCount()->getData() > 0)
		{	
			$booking_arr = pjBookingTicketModel::factory()
				->select("t1.*, t2.content as ticket, t3.uuid, t3.status, t3.c_name, t4.name AS seat_name")
				->join('pjMultiLang', "t2.model='pjTicket' AND t2.foreign_id=t1.ticket_id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjBooking', 't3.id=t1.booking_id', 'left outer')
				->join('pjSeat', 't1.seat_id=t4.id', 'left out')
				->where("(t1.booking_id IN(SELECT `TB`.id FROM `".pjBookingModel::factory()->getTable()."` AS `TB` WHERE `TB`.event_id='".$event_id."'))")
				->orderBy("t3.created ASC")
				->findAll()
				->getData();
		}else{
			$booking_arr = pjBookingTicketModel::factory()
				->select("t1.*, t2.content as ticket, t3.uuid, t3.status, t3.c_name")
				->join('pjMultiLang', "t2.model='pjTicket' AND t2.foreign_id=t1.ticket_id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjBooking', 't3.id=t1.booking_id', 'left outer')
				->where("(t1.booking_id IN(SELECT `TB`.id FROM `".pjBookingModel::factory()->getTable()."` AS `TB` WHERE `TB`.event_id='".$event_id."'))")
				->orderBy("t3.created ASC")
				->findAll()
				->getData();
		}

		return compact('event_arr', 'booking_arr');
	}
}
?>