<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminBookings extends pjAdmin
{                  
	public function pjActionCheckUniqueId()
	{
		$this->setAjax(true);
		
		if ($this->isXHR() && isset($_GET['uuid']))
		{
			$pjBookingModel = pjBookingModel::factory();
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$pjBookingModel->where('t1.id !=', $_GET['id']);
			}
			echo $pjBookingModel->where('t1.uuid', $_GET['uuid'])->findCount()->getData() == 0 ? 'true' : 'false';
		}
		exit;
	}
	
	public function pjActionGetBooking()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjBookingModel = pjBookingModel::factory()
				->join('pjMultiLang', "t2.model='pjEvent' AND t2.foreign_id=t1.event_id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer');
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjBookingModel->where('t1.uuid LIKE', "%$q%");
				$pjBookingModel->orWhere('t1.c_name LIKE', "%$q%");
				$pjBookingModel->orWhere('t1.c_email LIKE', "%$q%");
				$pjBookingModel->orWhere('t1.c_phone LIKE', "%$q%");
			}
						
			if (isset($_GET['event_id']) && (int) $_GET['event_id'] > 0)
			{
				$pjBookingModel->where('t1.event_id', $_GET['event_id']);
			}
			
			if (isset($_GET['uuid']) && $_GET['uuid'] != '')
			{
				$uuid = pjObject::escapeString($_GET['uuid']);
				$pjBookingModel->where('t1.uuid LIKE', "%$uuid%");
			}
			if (isset($_GET['c_name']) && $_GET['c_name'] != '')
			{
				$customer_name = pjObject::escapeString($_GET['c_name']);
				$pjBookingModel->where('t1.c_name LIKE', "%$customer_name%");
			}
			if (isset($_GET['c_email']) && $_GET['c_email'] != '')
			{
				$customer_email = pjObject::escapeString($_GET['c_email']);
				$pjBookingModel->where('t1.c_email LIKE', "%$customer_email%");
			}
			if (isset($_GET['status']) && !empty($_GET['status']))
			{
				$pjBookingModel->where('t1.status', $_GET['status']);
			}
			
			$column = 'created';
			$direction = 'DESC';
			$allowed_columns = array('c_name', 'title', 'cnt_tickets', 'total', '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 = $pjBookingModel->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 = $pjBookingModel
				->select("t1.id, t1.uuid, t1.c_name, t1.total, t1.status, t2.content as title, (SELECT COUNT(`TBT`.ticket_id) FROM `".pjBookingTicketModel::factory()->getTable()."` AS `TBT` WHERE `TBT`.booking_id=t1.id) AS cnt_tickets")
				->orderBy("$column $direction")->limit($rowCount, $offset)->findAll()->getData();
			
			foreach($data as $k => $v)
			{
				$v['total'] = pjUtil::formatCurrencySign($v['total'], $this->option_arr['o_currency']);	
				$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('pjAdminBookings.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionExportBooking()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjBookingModel::factory()
				->whereIn('id', $_POST['record'])
				->findAll()
				->getData();

			if (!empty($arr)) {
				foreach ($arr as $k => $booking) {
					$bookingTickets = pjBookingTicketModel::factory()
						->select('
							t1.*,
							t2.content as name
						')
						->join('pjMultiLang', 't2.model = "pjTicket" AND t2.foreign_id = t1.ticket_id AND t2.field = "title" AND t2.locale = ' . $this->getLocaleId())
						->where('t1.booking_id', $booking['id'])
						->findAll()
						->getData();

					$tickets = array();
					foreach ($bookingTickets as $i => $bookingTicket) {
						$tickets[$i] .= $bookingTicket['name'];
						if (!empty($bookingTicket['seat_id'])) {
							$tickets[$i] .= ': ' . $bookingTicket['seat_id'];
						}
					}

					$arr[$k]['tickets'] = implode('; ', $tickets);
				}
			}

			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Bookings-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			$pjEventModel = pjEventModel::factory();
			
			if (isset($_POST['booking_create']))
			{
				$data = array();
				
				$pjBookingModel = pjBookingModel::factory();
				
				$uuid = pjUtil::uuid();
				$data['uuid'] = $uuid;
				$data['ip']= pjUtil::getClientIp();
				
				$post = array_merge($_POST, $data);
				
				$id = $pjBookingModel->setAttributes($post)->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					if(isset($_POST['count']) && is_array($_POST['count']) && count($_POST['count']))
					{
						$pjBookingTicketModel = pjBookingTicketModel::factory();
						
						foreach($_POST['count'] as $ticket_id => $count)
						{
							if((int) $count > 0)
							{
								$booking_ticket_data = array();
								$booking_ticket_data['booking_id'] = $id;
								$booking_ticket_data['ticket_id'] = $ticket_id;
								$booking_ticket_data['donation'] = (isset($_POST['donation'][$ticket_id]) && (float) $_POST['donation'][$ticket_id]) > 0 ? $_POST['donation'][$ticket_id] : ":NULL";
								$booking_ticket_data['unit_price'] = (isset($_POST['unit_price'][$ticket_id]) && (float) $_POST['unit_price'][$ticket_id]) > 0 ? $_POST['unit_price'][$ticket_id] : ":NULL";
								
								if(isset($_POST['seat_id'][$ticket_id]) && is_array($_POST['seat_id'][$ticket_id]) && count($_POST['seat_id'][$ticket_id]))
								{
									$i = 1;
									foreach($_POST['seat_id'][$ticket_id] as $key => $seat_id)
									{
										$booking_ticket_data['seat_id'] = $seat_id;
										$booking_ticket_data['attendee_name'] = isset($_POST['attendee'][$ticket_id][$i]) ? $_POST['attendee'][$ticket_id][$i] : $post['c_name'];
										$booking_ticket_data['ticket_code'] = $uuid . '-' . $ticket_id . '-' . ($key + 1);
										$booking_ticket_data['is_used'] = "F";
										$pjBookingTicketModel->reset()->setAttributes($booking_ticket_data)->insert();
										$i++;
									}
								}else{
									for($i = 1; $i <= (int) $count; $i++)
									{
										$booking_ticket_data['seat_id'] = ":NULL";
										$booking_ticket_data['attendee_name'] = isset($_POST['attendee'][$ticket_id][$i]) ? $_POST['attendee'][$ticket_id][$i] : $post['c_name'];
										$booking_ticket_data['ticket_code'] = $uuid . '-' . $ticket_id . '-' . $i;
										$booking_ticket_data['is_used'] = "F";
										$pjBookingTicketModel->reset()->setAttributes($booking_ticket_data)->insert();
									}
								}
							}
						}
					}
					
					$arr = pjAppController::pjActionGetBookingDetails($id);
					
					$this->pjActionGenerateInvoice($arr);
					$this->buildPdfTickets($arr);
					
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionIndex&err=AR03");
				} else {
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionIndex&err=AR04");
				}
			}else{
				$pjBookingModel = pjBookingModel::factory();
				$pjEventModel = pjEventModel::factory();
				
				$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')
					->orderBy('`country_title` ASC')
					->findAll()
					->getData();
				
				$event_arr = pjEventModel::factory()
					->select(" t1.*, t2.content as title, (SELECT COUNT(`TC`.id) FROM `".pjCodeModel::factory()->getTable()."` AS `TC` WHERE `TC`.event_id=t1.id) AS cnt_codes")
					->join('pjMultiLang', "t2.model='pjEvent' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where("t1.status", "T")
					->orderBy("title ASC")
					->findAll()
					->getData();
				
				$this->set('event_arr', $event_arr);
				$this->set('country_arr', $country_arr);
				
				$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminBookings.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			
			if (isset($_POST['booking_update']))
			{
				$data = array();
				
				$pjBookingModel = pjBookingModel::factory();
				
				$data['ip']= pjUtil::getClientIp();
				
				$post = array_merge($_POST, $data);
				
				$pjBookingModel->set('id', $_POST['id'])->modify($post);
				
				if(isset($_POST['count']) && is_array($_POST['count']) && count($_POST['count']))
				{
					$pjBookingTicketModel = pjBookingTicketModel::factory();
				
					$pjBookingTicketModel->where('booking_id', $_POST['id'])->eraseAll();
					foreach($_POST['count'] as $ticket_id => $count)
					{
						if((int) $count > 0)
						{
							$booking_ticket_data = array();
							$booking_ticket_data['booking_id'] = $_POST['id'];
							$booking_ticket_data['ticket_id'] = $ticket_id;
							$booking_ticket_data['donation'] = (isset($_POST['donation'][$ticket_id]) && (float) $_POST['donation'][$ticket_id]) > 0 ? $_POST['donation'][$ticket_id] : ":NULL";
							$booking_ticket_data['unit_price'] = (isset($_POST['unit_price'][$ticket_id]) && (float) $_POST['unit_price'][$ticket_id]) > 0 ? $_POST['unit_price'][$ticket_id] : ":NULL";
								
							if(isset($_POST['seat_id'][$ticket_id]) && is_array($_POST['seat_id'][$ticket_id]) && count($_POST['seat_id'][$ticket_id]))
							{
								$i = 1;
								foreach($_POST['seat_id'][$ticket_id] as $key => $seat_id)
								{
									$booking_ticket_data['seat_id'] = $seat_id;
									$booking_ticket_data['attendee_name'] = isset($_POST['attendee'][$ticket_id][$i]) ? $_POST['attendee'][$ticket_id][$i] : $post['c_name'];
									$booking_ticket_data['ticket_code'] = $_POST['uuid'] . '-' . $ticket_id . '-' . ($key + 1);
									$pjBookingTicketModel->reset()->setAttributes($booking_ticket_data)->insert();
									$i++;
								}
							}else{
								for($i = 1; $i <= (int) $count; $i++)
								{
									$booking_ticket_data['seat_id'] = ":NULL";
									$booking_ticket_data['attendee_name'] = isset($_POST['attendee'][$ticket_id][$i]) ? $_POST['attendee'][$ticket_id][$i] : $post['c_name'];
									$booking_ticket_data['ticket_code'] = $_POST['uuid'] . '-' . $ticket_id . '-' . $i;
									$pjBookingTicketModel->reset()->setAttributes($booking_ticket_data)->insert();
								}
							}
						}
					}
				}
				
				$arr = $this->pjActionGetBookingDetails($_POST['id']);
				$this->deletePDFTickets($_POST['id'], $arr['uuid']);
				$this->buildPdfTickets($arr);
				
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionIndex&err=AR01");
			} else {
				
				$pjBookingModel = pjBookingModel::factory();
				if (isset($_REQUEST['id']) && (int) $_REQUEST['id'] > 0)
				{
					$pjBookingModel->where('t1.id', $_REQUEST['id']);
				} elseif (isset($_GET['uuid']) && !empty($_GET['uuid'])) {
					$pjBookingModel->where('t1.uuid', $_GET['uuid']);
				}
				$arr = $pjBookingModel
					->select(sprintf("t1.*,
						AES_DECRYPT(t1.cc_type, '%1\$s') AS `cc_type`,	
						AES_DECRYPT(t1.cc_num, '%1\$s') AS `cc_num`,
						AES_DECRYPT(t1.cc_exp_month, '%1\$s') AS `cc_exp_month`,
						AES_DECRYPT(t1.cc_exp_year, '%1\$s') AS `cc_exp_year`,
						AES_DECRYPT(t1.cc_code, '%1\$s') AS `cc_code`, t3.content as event_title", PJ_SALT))
					->join('pjEvent', 't2.id=t1.event_id')
					->join('pjMultiLang', "t3.model='pjEvent' AND t3.foreign_id=t1.event_id AND t3.field='title' AND t3.locale='".$this->getLocaleId()."'", 'left outer')
					->limit(1)
					->findAll()
					->getData();
					
				if (empty($arr))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionIndex&err=AR08");
				}
				$arr = $arr[0];
				
				$ticket_arr = pjTicketModel::factory()
					->select(sprintf("t1.*, t2.content as title, (SELECT COUNT(`TBT`.ticket_id) FROM `%1\$s` AS `TBT` WHERE `TBT`.ticket_id=t1.id AND `TBT`.booking_id IN (SELECT `TB`.id FROM `%2\$s` AS `TB` WHERE `TB`.event_id='%3\$s' AND (`TB`.status='confirmed' OR `TB`.status='pending') AND `TB`.id <> '%4\$s' ) ) AS cnt_booked ", pjBookingTicketModel::factory()->getTable(), pjBookingModel::factory()->getTable(), $arr['event_id'], $arr['id']) )
					->join('pjMultiLang', "t2.model='pjTicket' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('event_id', $arr['event_id'])
					->orderBy("title ASC")
					->findAll()
					->getData();
				
				$pjBookingTicketModel = pjBookingTicketModel::factory();
				
				$pjEventModel = pjEventModel::factory();
				$event_arr = $pjEventModel
					->select(" t1.*, t2.content as title, (SELECT COUNT(`TC`.id) FROM `".pjCodeModel::factory()->getTable()."` AS `TC` WHERE `TC`.event_id=t1.id) AS cnt_codes")
					->join('pjMultiLang', "t2.model='pjEvent' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where("t1.status", "T")
					->orderBy("title ASC")
					->findAll()
					->getData();
				
				$booking_ticket_arr = array();
				$booking_seat_arr = array();
				$booking_seat_name_arr = array();
				
				$event = $pjEventModel->reset()->find($arr['event_id'])->getData();
				if(!empty($event['map']))
				{
					$temp_booking_ticket_arr = $pjBookingTicketModel
						->select('t1.*, t2.content AS ticket, t3.attendee_name AS attendee_required, 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('pjTicket', 't1.ticket_id=t3.id', 'left out')
						->join('pjSeat', 't1.seat_id=t4.id', 'left out')
						->where('t1.booking_id', $arr['id'])
						->findAll()
						->getData();
					
					foreach($temp_booking_ticket_arr as $k => $v)
					{
						$booking_ticket_arr[$v['ticket_id']][] = $v;
						$booking_seat_arr[$v['ticket_id']][] = $v['seat_id'];
						$booking_seat_name_arr[$v['ticket_id']][] = $v['seat_name'];
					}
				}else{
					$temp_booking_ticket_arr = $pjBookingTicketModel
						->select('t1.*, t2.content AS ticket, t3.attendee_name AS attendee_required')
						->join('pjMultiLang', "t2.model='pjTicket' AND t2.foreign_id=t1.ticket_id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
						->join('pjTicket', 't1.ticket_id=t3.id', 'left out')
						->where('t1.booking_id', $arr['id'])
						->findAll()
						->getData();
					foreach($temp_booking_ticket_arr as $k => $v)
					{
						$booking_ticket_arr[$v['ticket_id']][] = $v;
					}
				}
				$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')
					->orderBy('`country_title` ASC')
					->findAll()
					->getData();
				
				
				$cnt_codes = pjCodeModel::factory()->where('t1.event_id', $arr['event_id'])->findCount()->getData();
				
				$this->set('invoice_arr', pjInvoiceModel::factory()
						->where('t1.order_id', $arr['uuid'])
						->findAll()
						->getData()
				);

				$pjMultiLangModel = pjMultiLangModel::factory();
				$lang_message = $pjMultiLangModel->reset()->select('t1.*')
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_email_confirmation_message')
					->limit(0, 1)
					->findAll()->getData();
				$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_email_confirmation_subject')
					->limit(0, 1)
					->findAll()->getData();
				if (count($lang_message) === 1 && count($lang_subject) === 1)
				{
					$this->set('has_confirm', true);
				}
				
				$lang_message = $pjMultiLangModel->reset()->select('t1.*')
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_email_payment_message')
					->limit(0, 1)
					->findAll()->getData();
				$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_email_payemnt_subject')
					->limit(0, 1)
					->findAll()->getData();
				if (count($lang_message) === 1 && count($lang_subject) === 1)
				{
					$this->set('has_payment', true);
				}
				
				$this->set('arr', $arr);
				$this->set('event_arr', $event_arr);
				$this->set('cnt_codes', $cnt_codes);
				$this->set('ticket_arr', $ticket_arr);
				$this->set('country_arr', $country_arr);
				$this->set('booking_ticket_arr', $booking_ticket_arr);
				$this->set('booking_seat_arr', $booking_seat_arr);
				$this->set('booking_seat_name_arr', $booking_seat_name_arr);
				$this->set('event', pjEventModel::factory()->find($arr['event_id'])->getData());
				
				$this->appendJs('tinymce.min.js', PJ_THIRD_PARTY_PATH . 'tinymce/');
				$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
				$this->appendJs('pjAdminBookings.js');
			}
		}
	}
	
	public function pjActionDeleteBooking()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			$pjBookingModel = pjBookingModel::factory();
			$arr = $pjBookingModel->find($_GET['id'])->getData();
			if ($pjBookingModel->reset()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				$this->deletePDFTickets($arr['id'], $arr['uuid']);
				pjBookingPaymentModel::factory()->where('booking_id', $_GET['id'])->eraseAll();
				pjBookingTicketModel::factory()->where('booking_id', $_GET['id'])->eraseAll();
				
				$pjInvoiceModel = pjInvoiceModel::factory();
				$invoice_id_arr = $pjInvoiceModel->where('order_id', $arr['uuid'])->findAll()->getDataPair(null, 'id');
				if(!empty($invoice_id_arr))
				{
					pjInvoiceItemModel::factory()->whereIn('invoice_id', $invoice_id_arr)->eraseAll();
					$pjInvoiceModel->reset()->where('order_id', $arr['uuid'])->eraseAll();
				}
				
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteBookingBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				$pjBookingModel = pjBookingModel::factory();
				$arr = $pjBookingModel->whereIn('id', $_POST['record'])->findAll()->getData();
				$uuid_arr = $pjBookingModel->reset()->whereIn('id', $_POST['record'])->findAll()->getDataPair(null, 'uuid');
				foreach($arr as $k => $v)
				{
					$this->deletePDFTickets($v['id'], $v['uuid']);
				}
				if(!empty($uuid_arr))
				{
					$pjInvoiceModel = pjInvoiceModel::factory();
					$invoice_id_arr = $pjInvoiceModel->whereIn('order_id', $uuid_arr)->findAll()->getDataPair(null, 'id');
					if(!empty($invoice_id_arr))
					{
						pjInvoiceItemModel::factory()->whereIn('invoice_id', $invoice_id_arr)->eraseAll();
						$pjInvoiceModel->reset()->whereIn('order_id', $uuid_arr)->eraseAll();
					}
				}
				$pjBookingModel->reset()->whereIn('id', $_POST['record'])->eraseAll();
				pjBookingPaymentModel::factory()->whereIn('booking_id', $_POST['record'])->eraseAll();
				pjBookingTicketModel::factory()->whereIn('booking_id', $_POST['record'])->eraseAll();
				
			}
		}
		exit;
	}
	
	public function pjActionSaveBooking()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			pjBookingModel::factory()->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
		}
		exit;
	}
	
	public function pjActionGetTickets()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if(isset($_GET['event_id']) && (int) $_GET['event_id'] > 0)
			{
				$ticket_arr = pjTicketModel::factory()
					->select(sprintf("t1.*, t2.content as title, (SELECT COUNT(`TBT`.ticket_id) FROM `%1\$s` AS `TBT` WHERE `TBT`.ticket_id=t1.id AND `TBT`.booking_id IN (SELECT `TB`.id FROM `%2\$s` AS `TB` WHERE `TB`.event_id='%3\$s' AND (`TB`.status='confirmed' OR `TB`.status='pending') ) ) AS cnt_booked ", pjBookingTicketModel::factory()->getTable(), pjBookingModel::factory()->getTable(), $_GET['event_id']) )
					->join('pjMultiLang', "t2.model='pjTicket' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('event_id', $_GET['event_id'])
					->orderBy("title ASC")
					->findAll()
					->getData();
				
				$this->set('event', pjEventModel::factory()->find($_GET['event_id'])->getData());
				$this->set('ticket_arr', $ticket_arr);
			}
		}
	}
	
	public function pjActionJoin()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if(isset($_POST['event_id']) && (int) $_POST['event_id'] > 0 && isset($_POST['ticket_id']) && (int) $_POST['ticket_id'] > 0)
			{
				$_POST['created'] = date('Y-m-d H:i:s');
				$id = pjWaitlistModel::factory()->setAttributes($_POST)->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$response['code'] = 200;
				}else{
					$response['code'] = 100;
				}
			}else{
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionGetSeats()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if(isset($_GET['event_id']) && (int) $_GET['event_id'] > 0 && isset($_GET['ticket_id']) && (int) $_GET['ticket_id'] > 0)
			{
				$and_where = '';
				if(isset($_POST['id']) && (int) $_POST['id'] > 0)
				{
					$and_where = ' AND TB.id <>' . $_POST['id'];
				}
				$seat_arr = pjSeatTicketModel::factory()
					->select("t1.*, t2.*, (SELECT COUNT(TBS.seat_id) FROM `".pjBookingTicketModel::factory()->getTable()."` AS `TBS` WHERE TBS.seat_id=t1.seat_id AND TBS.booking_id IN(SELECT TB.id FROM `".pjBookingModel::factory()->getTable()."` AS `TB` WHERE `TB`.event_id=".$_GET['event_id']." AND (TB.status='confirmed' OR TB.status='pending')$and_where )) AS booked_seats")
					->join("pjSeat", "t1.seat_id=t2.id", 'left')
					->where('t2.event_id', $_GET['event_id'])
					->where("t1.ticket_id", $_GET['ticket_id'])
					->findAll()
					->getData();
				
				$seat_selected_id_arr = array();
				if(isset($_POST['seat_id']) && is_array($_POST['seat_id']) && count($_POST['seat_id']))
				{
					$seat_selected_id_arr = $_POST['seat_id'];
				}
				
				$this->set('seat_arr', $seat_arr);
				$this->set('seat_selected_id_arr', $seat_selected_id_arr);
				$this->set('event_arr', pjEventModel::factory()->find($_GET['event_id'])->getData());
			}
		}
	}
	
	public function pjActionApplyCode()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if(isset($_GET['event_id']) && (int) $_GET['event_id'] > 0 && isset($_GET['discount_code']) && $_GET['discount_code'] != '')
			{
				$pjCodeModel = pjCodeModel::factory();
				
				$arr = pjCodeModel::factory()->checkCode($_GET['event_id'], $_GET['discount_code'], $this->option_arr);
				
				pjAppController::jsonResponse($arr);
			}else{
				pjAppController::jsonResponse(array('status' => 'ERR'));
			}
		}
		exit;
	}
	
	public function pjActionConfirmation()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['send_confirm']) && !empty($_POST['to']) && !empty($_POST['from']) &&
					!empty($_POST['subject']) && !empty($_POST['message']))
			{
				$Email = new pjEmail();
				$Email->setContentType('text/html');
				if ($this->option_arr['o_send_email'] == 'smtp')
				{
					$Email
						->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']);
				}
	
				$subject = $_POST['subject'];
				$message = $_POST['message'];
				if (function_exists("get_magic_quotes_gpc") && get_magic_quotes_gpc())
				{
					$subject = stripslashes($_POST['subject']);
					$message = stripslashes($_POST['message']);
				}
	
				$r = $Email
					->setTo($_POST['to'])
					->setFrom($_POST['from'])
					->setSubject($subject)
					->send($message);
					
				if ($r)
				{
					pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Email has been sent.'));
				}
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Email failed to send.'));
			}
				
			if (isset($_GET['booking_id']) && (int) $_GET['booking_id'] > 0)
			{
				$pjMultiLangModel = pjMultiLangModel::factory();
				$lang_message = $pjMultiLangModel->reset()->select('t1.*')
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_email_confirmation_message')
					->limit(0, 1)
					->findAll()->getData();
				$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_email_confirmation_subject')
					->limit(0, 1)
					->findAll()->getData();
				
				if (count($lang_message) === 1 && count($lang_subject) === 1)
				{
					$booking_arr = $this->pjActionGetBookingDetails($_GET['booking_id']);
					
					$tokens = pjAppController::getTokens($this->option_arr, $booking_arr, PJ_SALT, $this->getLocaleId());
		
					$subject_client = str_replace($tokens['search'], $tokens['replace'], $lang_subject[0]['content']);
					$message_client = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
		
					$this->set('arr', array(
							'to' => $booking_arr['c_email'],
							'from' => $this->getAdminEmail(),
							'message' => $message_client,
							'subject' => $subject_client
					));
				}
			} else {
				exit;
			}
		}
	}
	
	public function pjActionSendPayment()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['send_payment']) && !empty($_POST['to']) && !empty($_POST['from']) &&
					!empty($_POST['subject']) && !empty($_POST['message']))
			{
				$Email = new pjEmail();
				$Email->setContentType('text/html');
				if ($this->option_arr['o_send_email'] == 'smtp')
				{
					$Email
						->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']);
				}
	
				$subject = $_POST['subject'];
				$message = $_POST['message'];
				if (function_exists("get_magic_quotes_gpc") && get_magic_quotes_gpc())
				{
					$subject = stripslashes($_POST['subject']);
					$message = stripslashes($_POST['message']);
				}
	
				$r = $Email
					->setTo($_POST['to'])
					->setFrom($_POST['from'])
					->setSubject($subject)
					->send($message);
					
				if ($r)
				{
					pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Email has been sent.'));
				}
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Email failed to send.'));
			}
	
			if (isset($_GET['booking_id']) && (int) $_GET['booking_id'] > 0)
			{
				$pjMultiLangModel = pjMultiLangModel::factory();
				$lang_message = $pjMultiLangModel->reset()->select('t1.*')
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_email_payment_message')
					->limit(0, 1)
					->findAll()->getData();
				$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_email_payment_subject')
					->limit(0, 1)
					->findAll()->getData();
	
				if (count($lang_message) === 1 && count($lang_subject) === 1)
				{
					$booking_arr = $this->pjActionGetBookingDetails($_GET['booking_id']);
					
					$tokens = pjAppController::getTokens($this->option_arr, $booking_arr, PJ_SALT, $this->getLocaleId());
	
					$subject_client = str_replace($tokens['search'], $tokens['replace'], $lang_subject[0]['content']);
					$message_client = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
	
					$this->set('arr', array(
							'to' => $booking_arr['c_email'],
							'from' => $this->getAdminEmail(),
							'message' => $message_client,
							'subject' => $subject_client
					));
				}
			} else {
				exit;
			}
		}
	}
	
	public function pjActionBarcode()
	{
		$this->checkLogin();
	
		if ($this->isAdmin() || $this->isEditor())
		{
			if(isset($_POST['read_barcode']))
			{
				$ticket_arr = pjBookingTicketModel::factory()
					->where('ticket_code', $_POST['barcode_label'])
					->findAll()
					->getData();
				
				$status = 1;
					
				if(count($ticket_arr) > 0)
				{
					$arr = $this->pjActionGetBookingDetails($ticket_arr[0]['booking_id']);
					$arr['ticket_id'] = $ticket_arr[0]['ticket_id'];
					$arr['is_used'] = $ticket_arr[0]['is_used'];
					$arr['booking_ticket_id'] = $ticket_arr[0]['id'];
					
					if($arr['status'] != 'confirmed')
					{
						$status = 2;
					}else if($arr['is_used'] == 'T'){
						$status = 3;
					}
						
					$this->set('arr', $arr);
				}else{
					$status = 4;
				}
				$this->set('ticket_status', $status);
			}
				
			$this->appendJs('pjAdminBookings.js');
		} else {
			$this->set('status', 2);
		}
	}
	public function pjActionSetUseTicket()
	{
		$this->setAjax(true);
	
		$json_arr = array();
	
		pjBookingTicketModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll(array('is_used' => 'T'));
		$json_arr['status'] = 1;
	
		pjAppController::jsonResponse($json_arr);
	}
	
	public function pjActionGetAttendees()
	{
		$this->setAjax(true);
	
		$ticket_arr = pjTicketModel::factory()
			->select("t1.*, t2.content as title")
			->join('pjMultiLang', "t2.model='pjTicket' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
			->find($_GET['ticket_id'])
			->getData();
		$this->set('ticket_arr', $ticket_arr);
	}
}
?>