<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminBookings extends pjAdmin
{
	public function pjActionCheckID()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (!isset($_GET['uuid']) || empty($_GET['uuid']))
			{
				echo 'false';
				exit;
			}
			$pjBookingModel = pjBookingModel::factory()->where('t1.uuid', $_GET['uuid']);
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$pjBookingModel->where('t1.id !=', $_GET['id']);
			}
			echo $pjBookingModel->findCount()->getData() == 0 ? 'true' : 'false';
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			$pjLocationModel = pjLocationModel::factory();
			$pickup_arr = $pjLocationModel
				->join('pjMultiLang', "t2.model='pjLocation' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->select("t1.*, t2.content as title")
				->where('t1.type', 'DA')
				->where('t1.status', 'T')
				->orderBy("title ASC")
				->findAll()->getData();
			$this->set('pickup_arr', $pickup_arr);
			
			$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'chosen/');
			$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
			
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminBookings.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetBooking()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjBookingModel = pjBookingModel::factory()
				->join('pjMultiLang', "t2.model='pjLocation' AND t2.foreign_id=t1.location_id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjMultiLang', "t3.model='pjLocation' AND t3.foreign_id=t1.dropoff_id AND t3.field='title' AND t3.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjClient', "t4.id=t1.client_id", 'left');
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjBookingModel->where("(t4.fname LIKE '%$q%' OR t4.lname LIKE '%$q%' OR t4.email LIKE '%$q%')");
			}
			
			if (isset($_GET['client_id']) && (int) $_GET['client_id'] > 0)
			{
				$client_id = pjObject::escapeString($_GET['client_id']);
				$pjBookingModel->where("(t1.client_id='".$client_id."')");
			}
			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('confirmed','cancelled','pending')))
			{
				$pjBookingModel->where('t1.status', $_GET['status']);
			}

			if (isset($_GET['name']) && !empty($_GET['name']))
			{
				$q = pjObject::escapeString($_GET['name']);
				$pjBookingModel->where('t4.fname LIKE', "%$q%");
				$pjBookingModel->orWhere('t4.lname LIKE', "%$q%");
			}
			if (isset($_GET['email']) && !empty($_GET['email']))
			{
				$q = pjObject::escapeString($_GET['email']);
				$pjBookingModel->where('t4.email LIKE', "%$q%");
			}
			if (isset($_GET['phone']) && !empty($_GET['phone']))
			{
				$q = pjObject::escapeString($_GET['phone']);
				$pjBookingModel->where('t4.phone LIKE', "%$q%");
			}
			if (isset($_GET['date']) && !empty($_GET['date']))
			{
				$date = pjUtil::formatDate(pjObject::escapeString($_GET['date']), $this->option_arr['o_date_format']);
				$pjBookingModel->where("((DATE_FORMAT(t1.booking_date, '%Y-%m-%d')='$date') OR (t1.has_return='T' AND DATE_FORMAT(t1.return_date, '%Y-%m-%d')='$date'))");
			}
			if (isset($_GET['location_id']) && !empty($_GET['location_id']))
			{
				$location_id = pjObject::escapeString($_GET['location_id']);
				$pjBookingModel->where("(t1.location_id='".$location_id."')");
			}
			if (isset($_GET['dropoff_id']) && !empty($_GET['dropoff_id']))
			{
				$dropoff_id = pjObject::escapeString($_GET['dropoff_id']);
				$pjBookingModel->where("(t1.dropoff_id='".$dropoff_id."')");
			}
			
			$column = 'created';
			$direction = 'DESC';
			if (isset($_GET['direction']) && isset($_GET['column']) && 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 = array();
			
			$data = $pjBookingModel
				->select("t1.*, t2.content as from_location, t3.content as to_location, t4.fname, t4.lname, t4.email,t4.phone,
							AES_DECRYPT(t1.cc_type, '".PJ_SALT."') AS `cc_type`,
							AES_DECRYPT(t1.cc_num, '".PJ_SALT."') AS `cc_num`,
							AES_DECRYPT(t1.cc_exp_month, '".PJ_SALT."') AS `cc_exp_month`,
							AES_DECRYPT(t1.cc_exp_year, '".PJ_SALT."') AS `cc_exp_year`,
							AES_DECRYPT(t1.cc_code, '".PJ_SALT."') AS `cc_code`
						")
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();
				
			foreach($data as $k => $v)
			{
				$client_arr = array();
				if(!empty($v['c_fname']) || !empty($v['fname']))
				{
					$client_arr[] = !empty($v['client_id']) ? pjSanitize::clean($v['fname']) : pjSanitize::clean($v['c_fname']) ;
				}
				if(!empty($v['c_lname']) || !empty($v['lname']))
				{
					$client_arr[] = !empty($v['client_id']) ? pjSanitize::clean($v['lname']) : pjSanitize::clean($v['c_lname']) ;
				}
				$v['client'] = join(" ", $client_arr) . "<br/>" . (!empty($v['client_id']) ? pjSanitize::clean($v['email']) : pjSanitize::clean($v['lname']) );
				$v['pickup_dropoff'] = $v['from_location'] . "<br/>" . $v['to_location'];
				if($v['has_return'] == 'T')
				{
					$v['date_time'] = date($this->option_arr['o_date_format'] . ', ' . $this->option_arr['o_time_format'], strtotime($v['booking_date'] . ' ' . $v['booking_time'])) . '<br/>' . strtolower(__('lblReturn', true, false)) . ': ' . date($this->option_arr['o_date_format'] . ', ' . $this->option_arr['o_time_format'], strtotime($v['return_date'] . ' ' . $v['return_time'])) ;
				}else{
					$v['date_time'] = date($this->option_arr['o_date_format'] . ', ' . $this->option_arr['o_time_format'], strtotime($v['booking_date'] . ' ' . $v['booking_time']));
				}
				$data[$k] = $v;
			}
						
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionSaveBooking()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjBookingModel = pjBookingModel::factory();
			$arr = $pjBookingModel->find($_GET['id'])->getData();
			if(empty($arr['return_id']))
			{
				$pjBookingModel->reset()->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
				$pjBookingModel->reset()->where('return_id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
			}else{
				$pjBookingModel->reset()->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
				$pjBookingModel->reset()->where('id', $arr['return_id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
			}
		}
		exit;
	}
	
	public function pjActionExportBooking()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjBookingModel::factory()->whereIn('id', $_POST['record'])->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Bookings-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionPrint()
	{
		$this->checkLogin();
		$this->setLayout('pjActionPrint');
		$transfer_arr = array();
		
		if ((isset($_GET['record']) && $_GET['record'] != '') || isset($_GET['today']) || isset($_GET['id']))
		{
			$pjBookingModel = pjBookingModel::factory()
				->reset()
				->join('pjMultiLang', "t2.model='pjLocation' AND t2.foreign_id=t1.location_id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjMultiLang', "t3.model='pjLocation' AND t3.foreign_id=t1.dropoff_id AND t3.field='title' AND t3.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjMultiLang', "t4.model='pjLine' AND t4.foreign_id=t1.line_id AND t4.field='title' AND t4.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjMultiLang', "t5.model='pjLine' AND t5.foreign_id=t1.return_line_id AND t5.field='title' AND t5.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjClient', "t6.id=t1.client_id", 'left outer')
				->join('pjMultiLang', "t7.model='pjCountry' AND t7.foreign_id=t6.country_id AND t7.field='name' AND t7.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjMultiLang', "t8.model='pjLocation' AND t8.foreign_id=t1.location_id AND t8.field='address' AND t8.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjMultiLang', "t9.model='pjLocation' AND t9.foreign_id=t1.dropoff_id AND t9.field='address' AND t9.locale='".$this->getLocaleId()."'", 'left outer')
				->select("t1.*, t2.content as from_location, t3.content as to_location, t4.content as line, t5.content as return_line, 
							t7.content as country, t8.content as from_address, t9.content as to_address,
							t6.title, t6.fname, t6.lname, t6.email,t6.phone, t6.company, t6.address, t6.city, t6.state, t6.zip");
						
			if(!isset($_GET['id']))
			{
				if (isset($_GET['record']) && $_GET['record'] != '')
				{
					$pjBookingModel->whereIn("t1.id", explode(",", $_GET['record']));			
				}else{
					$pjBookingModel->where("(DATE_FORMAT(t1.booking_date, '%Y-%m-%d')=DATE_FORMAT(NOW(), '%Y-%m-%d'))")	;
					$pjBookingModel->where("t1.status <> 'cancelled'");
				}
			}else{
				$pjBookingModel->where("t1.id", $_GET['id']);
			}
			$transfer_arr = $pjBookingModel
				->orderBy("t1.created DESC")
				->findAll()
				->getData();
		}		
		$this->set('transfer_arr', $transfer_arr);
	}
	
	public function pjActionDeleteBooking()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			$pjBookingModel = pjBookingModel::factory();
			if ($pjBookingModel->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				$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();
				$pjBookingModel->whereIn('id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['booking_create']))
			{
				$pjBookingModel = pjBookingModel::factory();
				
				$data = array();
				$data['uuid'] = pjUtil::uuid();
				$data['ip'] = pjUtil::getClientIp();
				$data['booking_date'] = pjUtil::formatDate($_POST['booking_date'], $this->option_arr['o_date_format']);
				if(isset($_POST['has_return']))
				{
					$data['return_date'] = pjUtil::formatDate($_POST['return_date'], $this->option_arr['o_date_format']);
					$data['has_return'] = 'T';
				}else{
					$data['has_return'] = 'F';
					$data['return_date'] = ':NULL';
					$data['return_time'] = ':NULL';
					$data['return_line_id'] = ':NULL';
				}
				
				if(!isset($_POST['client_id']) || (isset($_POST['client_id']) && $_POST['client_id'] == ''))
				{
					$c_data = array();
					$c_data['title'] = isset($_POST['c_title']) ? $_POST['c_title'] : ':NULL';
					$c_data['fname'] = isset($_POST['c_fname']) ? $_POST['c_fname'] : ':NULL';
					$c_data['lname'] = isset($_POST['c_lname']) ? $_POST['c_lname'] : ':NULL';
					$c_data['email'] = isset($_POST['c_email']) ? $_POST['c_email'] : ':NULL';
					$c_data['password'] = pjUtil::getRandomPassword(6);
					$c_data['phone'] = isset($_POST['c_phone']) ? $_POST['c_phone'] : ':NULL';
					$c_data['status'] = 'T';
					if($c_data['email'] != ':NULL')
					{
						$pjClientModel = pjClientModel::factory();
						$client_arr = $pjClientModel->where('email', $c_data['email'])->limit(1)->findAll()->getData();
						if(count($client_arr) == 1)
						{
							$data['client_id'] = $client_arr[0]['id'];
						}else{
							$client_id = $pjClientModel->reset()->setAttributes($c_data)->insert()->getInsertId();
							if ($client_id !== false && (int) $client_id > 0)
							{
								$data['client_id'] = $client_id;
								pjAppController::pjActionAccountSend($this->option_arr, $client_id, PJ_SALT, $this->getLocaleId());
							}
						}
					}
				}
				$data['sub_total'] = pjUtil::convertToMySQLNumber($_POST['sub_total'], $this->option_arr);
				$data['tax'] = pjUtil::convertToMySQLNumber($_POST['tax'], $this->option_arr);
				$data['total'] = pjUtil::convertToMySQLNumber($_POST['total'], $this->option_arr);
				$data['deposit'] = pjUtil::convertToMySQLNumber($_POST['deposit'], $this->option_arr);
				
				$id = pjBookingModel::factory(array_merge($_POST, $data))->insert()->getInsertId();
				
				if ($id !== false && (int) $id > 0)
				{
					$err = 'ABB03';
				}else{
					$err = 'ABB04';
				}
				
				pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminBookings&action=pjActionIndex&err=$err");
			}else{
				$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();
						
				$this->set('country_arr', $country_arr);
				
				$client_arr = pjClientModel::factory()->select('t1.*')->orderBy('`fname` ASC')->findAll()->getData();
				
				$this->set('client_arr', $client_arr);
				
				$pjLocationModel = pjLocationModel::factory();
				$da_arr = $pjLocationModel
					->join('pjMultiLang', "t2.model='pjLocation' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->select("t1.*, t2.content as title")
					->where('t1.type', 'DA')
					->where('t1.status', 'T')
					->orderBy("title ASC")
					->findAll()->getData();
				$this->set('da_arr', $da_arr);
				
				$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendJs('jquery.ui.timepicker.js', PJ_THIRD_PARTY_PATH . 'timepicker/');
				$this->appendCss('jquery.ui.timepicker.css', PJ_THIRD_PARTY_PATH . 'timepicker/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('additional-methods.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('jquery.number.min.js', PJ_THIRD_PARTY_PATH . 'jquery_number/');
				$this->appendJs('pjAdminBookings.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['booking_update']))
			{
				$pjBookingModel = pjBookingModel::factory();
				
				$arr = $pjBookingModel->find($_POST['id'])->getData();
				if (empty($arr))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionIndex&err=ABB08");
				}
				$data = array();
				
				$data['ip'] = pjUtil::getClientIp();
				$data['booking_date'] = pjUtil::formatDate($_POST['booking_date'], $this->option_arr['o_date_format']);
				if(isset($_POST['has_return']))
				{
					$data['return_date'] = pjUtil::formatDate($_POST['return_date'], $this->option_arr['o_date_format']);
					$data['has_return'] = 'T';
				}else{
					$data['has_return'] = 'F';
					$data['return_date'] = ':NULL';
					$data['return_time'] = ':NULL';
					$data['return_line_id'] = ':NULL';
				}
				
				if(!isset($_POST['client_id']) || (isset($_POST['client_id']) && $_POST['client_id'] == ''))
				{
					$c_data = array();
					$c_data['title'] = isset($_POST['c_title']) ? $_POST['c_title'] : ':NULL';
					$c_data['fname'] = isset($_POST['c_fname']) ? $_POST['c_fname'] : ':NULL';
					$c_data['lname'] = isset($_POST['c_lname']) ? $_POST['c_lname'] : ':NULL';
					$c_data['email'] = isset($_POST['c_email']) ? $_POST['c_email'] : ':NULL';
					$c_data['password'] = pjUtil::getRandomPassword(6);
					$c_data['phone'] = isset($_POST['c_phone']) ? $_POST['c_phone'] : ':NULL';
					$c_data['status'] = 'T';
					if($c_data['email'] != ':NULL')
					{
						$pjClientModel = pjClientModel::factory();
						$client_arr = $pjClientModel->where('email', $c_data['email'])->limit(1)->findAll()->getData();
						if(count($client_arr) == 1)
						{
							$data['client_id'] = $client_arr[0]['id'];
						}else{
							$client_id = $pjClientModel->reset()->setAttributes($c_data)->insert()->getInsertId();
							if ($client_id !== false && (int) $client_id > 0)
							{
								$data['client_id'] = $client_id;
								pjAppController::pjActionAccountSend($this->option_arr, $client_id, PJ_SALT, $this->getLocaleId());
							}
						}
					}
				}
				$data['sub_total'] = pjUtil::convertToMySQLNumber($_POST['sub_total'], $this->option_arr);
				$data['tax'] = pjUtil::convertToMySQLNumber($_POST['tax'], $this->option_arr);
				$data['total'] = pjUtil::convertToMySQLNumber($_POST['total'], $this->option_arr);
				$data['deposit'] = pjUtil::convertToMySQLNumber($_POST['deposit'], $this->option_arr);
				
				$pjBookingModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll(array_merge($_POST, $data));
				
				$err = 'ABB01';
				pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminBookings&action=pjActionIndex&err=$err");
			}else{
				
				$arr = pjBookingModel::factory()
					->find($_GET['id'])
					->getData();

				if(count($arr) <= 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminBookings&action=pjActionIndex&err=ABB08");
				}
				
				$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();
						
				$this->set('country_arr', $country_arr);
				$this->set('arr', $arr);
				
				$pjClientModel = pjClientModel::factory();
				
				$client_arr = $pjClientModel->select('t1.*')->orderBy('`fname` ASC')->findAll()->getData();
				$this->set('client_arr', $client_arr);
				
				if((int) $arr['client_id'] > 0)
				{
					$client = $pjClientModel->reset()->find($arr['client_id'])->getData();
					$this->set('client', $client);
				}
				
				$pjLocationModel = pjLocationModel::factory();
				$da_arr = $pjLocationModel
					->join('pjMultiLang', "t2.model='pjLocation' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->select("t1.*, t2.content as title")
					->where('t1.type', 'DA')
					->where('t1.status', 'T')
					->orderBy("title ASC")
					->findAll()->getData();
				$this->set('da_arr', $da_arr);
				
				$location_id = $arr['location_id'];
				
				$pd_arr = array();
				$location_id_arr = pjLineDetailModel::factory()
					->select("DISTINCT t1.location_id")
					->where("(t1.line_id IN(SELECT `TL`.id FROM `".pjLineModel::factory()->getTable()."` AS `TL` WHERE `TL`.location_id='".$location_id."'))")
					->findAll()
					->getDataPair(null, 'location_id');
				if(!empty($location_id_arr))
				{
					$pd_arr = pjLocationModel::factory()
						->join('pjMultiLang', "t2.model='pjLocation' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
						->select("t1.*, t2.content as title")
						->whereIn('t1.id', $location_id_arr)
						->where('t1.type', 'PD')
						->where('t1.status', 'T')
						->orderBy("title ASC")
						->findAll()->getData();
					$this->set('pd_arr', $pd_arr);
				}
				
				$dropoff_id = $arr['dropoff_id'];
				
				$line_arr = pjLineModel::factory()
					->select("t1.*, t2.content as title")
					->join('pjMultiLang', "t2.model='pjLine' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where("t1.location_id", $location_id)
					->where("(t1.id IN(SELECT `TLD`.line_id FROM `".pjLineDetailModel::factory()->getTable()."` AS `TLD` WHERE `TLD`.`location_id`='".$dropoff_id."'))")
					->findAll()
					->getData();
				$this->set('line_arr', $line_arr);
				
				
				$line_id = $arr['line_id'];
				$traveling = $arr['traveling'];
				$booking_date = $arr['booking_date'];
				$result = $this->pjActionGetLineDetails($line_id, $location_id, $dropoff_id, $traveling, $booking_date);
				
				$this->set('line_detail_arr', $result['line_detail_arr']);
				$this->set('timetable_arr', $result['timetable_arr']);
				
				$pjBookingModel = pjBookingModel::factory();
				if(isset($_GET['id']) && (int) $_GET['id'] > 0)
				{
					$pjBookingModel->where("t1.id <>", $_GET['id']);
				}
				$booked_arr = $pjBookingModel
					->where("t1.location_id", $location_id)
					->where("t1.dropoff_id", $dropoff_id)
					->where("t1.status <>", 'cancelled')
					->where("( (t1.line_id='".$line_id."' AND t1.booking_date='".$booking_date."') OR (t1.return_line_id='".$line_id."' AND t1.return_date='".$booking_date."') )")
					->findAll()
					->getData();
				
				$booked_time_arr = array();
				$return_booked_time_arr = array();
				foreach($booked_arr as $k => $v)
				{
					$booked_time_arr[date("H:i", strtotime($v['booking_time']))] += (int) $v['passengers'];
					if(!empty($v['return_time']))
					{
						$booked_time_arr[date("H:i", strtotime($v['return_time']))] += (int) $v['passengers'];
					}
				}
				$this->set('booked_time_arr', $booked_time_arr);
				
				if($arr['has_return'] == 'T')
				{
					$booking_date = $arr['return_date'];
					$traveling = $arr['traveling'] == 'from' ? 'to' : 'from';
					$result = $this->pjActionGetLineDetails($arr['return_line_id'], $location_id, $dropoff_id, $traveling, $booking_date);
					
					$this->set('return_line_detail_arr', $result['line_detail_arr']);
					$this->set('return_timetable_arr', $result['timetable_arr']);
					
					$pjBookingModel->reset();
					if(isset($_GET['id']) && (int) $_GET['id'] > 0)
					{
						$pjBookingModel->where("t1.id <>", $_GET['id']);
					}
					$return_booked_arr = $pjBookingModel
						->where("t1.location_id", $location_id)
						->where("t1.dropoff_id", $dropoff_id)
						->where("t1.status <>", 'cancelled')
						->where("( (t1.line_id='".$arr['return_line_id']."' AND t1.booking_date='".$booking_date."') OR (t1.return_line_id='".$arr['return_line_id']."' AND t1.return_date='".$booking_date."') )")
						->findAll()
						->getData();
					foreach($return_booked_arr as $k => $v)
					{
						$return_booked_time_arr[date("H:i", strtotime($v['booking_time']))] += (int) $v['passengers'];
						if(!empty($v['return_time']))
						{
							$return_booked_time_arr[date("H:i", strtotime($v['return_time']))] += (int) $v['passengers'];
						}
					}
				}
				$this->set('return_booked_time_arr', $return_booked_time_arr);
				
				
				$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendJs('jquery.ui.timepicker.js', PJ_THIRD_PARTY_PATH . 'timepicker/');
				$this->appendCss('jquery.ui.timepicker.css', PJ_THIRD_PARTY_PATH . 'timepicker/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('jquery.number.min.js', PJ_THIRD_PARTY_PATH . 'jquery_number/');
				$this->appendJs('additional-methods.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminBookings.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetDropoff()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if(isset($_GET['location_id']) && (int) $_GET['location_id'] > 0)
			{
				$location_id = $_GET['location_id'];
				
				$location_id_arr = pjLineDetailModel::factory()
					->select("DISTINCT t1.location_id")
					->where("(t1.line_id IN(SELECT `TL`.id FROM `".pjLineModel::factory()->getTable()."` AS `TL` WHERE `TL`.location_id='".$location_id."'))")
					->findAll()
					->getDataPair(null, 'location_id');
				if(!empty($location_id_arr))
				{
					$pd_arr = pjLocationModel::factory()
						->join('pjMultiLang', "t2.model='pjLocation' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
						->select("t1.*, t2.content as title")
						->whereIn('t1.id', $location_id_arr)
						->where('t1.type', 'PD')
						->where('t1.status', 'T')
						->orderBy("title ASC")
						->findAll()->getData();
					$this->set('pd_arr', $pd_arr);
				}
			}
		}
	}
	public function pjActionGetLines()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if(isset($_GET['location_id']) && (int) $_GET['location_id'] > 0 && isset($_GET['dropoff_id']) && (int) $_GET['dropoff_id'] > 0)
			{
				$location_id = $_GET['location_id'];
				$dropoff_id = $_GET['dropoff_id'];
				$passengers = (int) $_GET['passengers'];
	
				$line_arr = pjLineModel::factory()
					->select("t1.*, t2.content as title")
					->join('pjMultiLang', "t2.model='pjLine' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where("t1.location_id", $location_id)
					->where("t1.seats >=", $passengers)
					->where("(t1.id IN(SELECT `TLD`.line_id FROM `".pjLineDetailModel::factory()->getTable()."` AS `TLD` WHERE `TLD`.`location_id`='".$dropoff_id."'))")
					->findAll()
					->getData();
				$this->set('line_arr', $line_arr);
			}
		}
	}
	public function pjActionGetTimes()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if(isset($_GET['line_id']) && (int) $_GET['line_id'] > 0 && isset($_GET['location_id']) && (int) $_GET['location_id'] > 0 && isset($_GET['booking_date']) && !empty($_GET['booking_date']))
			{
				$line_id = $_GET['line_id'];
				$location_id = $_GET['location_id'];
				$dropoff_id = $_GET['dropoff_id'];
				$traveling = $_GET['traveling'];
				$booking_date = pjUtil::formatDate($_GET['booking_date'], $this->option_arr['o_date_format']);
				$result = $this->pjActionGetLineDetails($line_id, $location_id, $dropoff_id, $traveling, $booking_date);
				$this->set('traveling', $traveling);
				$this->set('line_detail_arr', $result['line_detail_arr']);
				$this->set('timetable_arr', $result['timetable_arr']);
				
				$pjBookingModel = pjBookingModel::factory();
				if(isset($_GET['id']) && (int) $_GET['id'] > 0)
				{
					$pjBookingModel->where("t1.id <>", $_GET['id']);
				}
				$booked_arr = $pjBookingModel
					->where("t1.location_id", $location_id)
					->where("t1.dropoff_id", $dropoff_id)
					->where("t1.status <>", 'cancelled')
					->where("( (t1.line_id='".$line_id."' AND t1.booking_date='".$booking_date."') OR (t1.return_line_id='".$line_id."' AND t1.return_date='".$booking_date."') )")
					->findAll()
					->getData();
				$booked_time_arr = array();
				foreach($booked_arr as $k => $v)
				{
					$booked_time_arr[date("H:i", strtotime($v['booking_time']))] += $v['passengers'];
					if(!empty($v['return_time']))
					{
						$booked_time_arr[date("H:i", strtotime($v['return_time']))] += $v['passengers'];
					}
				}
				$this->set('booked_time_arr', $booked_time_arr);
				$this->set('line', pjLineModel::factory()->find($line_id)->getData());
			}
		}
	}
	
	public function pjActionResend()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['reminder']))
			{
				$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'])
					;
				}
				$pjEmail
					->setTo($_POST['to'])
					->setFrom($this->getFromEmail($this->option_arr))
					->setSubject($_POST['subject']);
				if ($pjEmail->send($_POST['message']))
				{
					$err = 'AB09';
				} else {
					$err = 'AB10';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionIndex&err=$err");
			} else {
				$arr = pjBookingModel::factory()
					->join('pjMultiLang', "t2.model='pjLocation' AND t2.foreign_id=t1.location_id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjMultiLang', "t3.model='pjLocation' AND t3.foreign_id=t1.dropoff_id AND t3.field='title' AND t3.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjMultiLang', "t4.model='pjLine' AND t4.foreign_id=t1.line_id AND t4.field='title' AND t4.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjMultiLang', "t5.model='pjLine' AND t5.foreign_id=t1.return_line_id AND t5.field='title' AND t5.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjClient', "t6.id=t1.client_id", 'left outer')
					->join('pjMultiLang', "t7.model='pjCountry' AND t7.foreign_id=t6.country_id AND t7.field='name' AND t7.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjMultiLang', "t8.model='pjLocation' AND t8.foreign_id=t1.location_id AND t8.field='address' AND t8.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjMultiLang', "t9.model='pjLocation' AND t9.foreign_id=t1.dropoff_id AND t9.field='address' AND t9.locale='".$this->getLocaleId()."'", 'left outer')
					->select("t1.*, t2.content as from_location, t3.content as to_location, t4.content as line, t5.content as return_line,
								t7.content as country, t8.content as from_address, t9.content as to_address,
								t6.title, t6.fname, t6.lname, t6.email,t6.phone, t6.company, t6.address, t6.city, t6.state, t6.zip")
					->find($_GET['id'])
					->getData();
				
				if (count($arr) === 0)
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionIndex&err=AB08");
				}
												 				
				$arr['data'] = pjAppController::getTokens($this->option_arr, $arr, PJ_SALT, $this->getLocaleId());
				
				$lang_message = pjMultiLangModel::factory()->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::factory()->select('t1.*')
											 ->where('t1.model','pjOption')
											 ->where('t1.locale', $this->getLocaleId())
											 ->where('t1.field', 'o_email_confirmation_subject')
											 ->limit(0, 1)
											 ->findAll()->getData();
				
				$this->set('arr', $arr);
				$this->set('lang_subject', $lang_subject[0]['content']);
				$this->set('lang_message', $lang_message[0]['content']);
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('tinymce.min.js', PJ_THIRD_PARTY_PATH . 'tinymce/');
				$this->appendJs('pjAdminBookings.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSendSms()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['send_sms']) && isset($_POST['to']) && !empty($_POST['to']) && !empty($_POST['message']) && !empty($_POST['id']))
			{
				$params = array(
					'text' => $_POST['message'],
					'type' => 'unicode',						
					'key' => md5($this->option_arr['private_key'] . PJ_SALT)
				);
				
				$params['number'] = $_POST['to'];
				$result = $this->requestAction(array('controller' => 'pjSms', 'action' => 'pjActionSend', 'params' => $params), array('return'));
			
				if (isset($result) && (int) $result === 1)
				{
					$err = 'AB11';
				}else{
					$err = 'AB12';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionUpdate&id=".$_POST['id']."&err=$err");
			} else {
				
				$arr = pjBookingModel::factory()
					->join('pjMultiLang', "t2.model='pjLocation' AND t2.foreign_id=t1.location_id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjMultiLang', "t3.model='pjLocation' AND t3.foreign_id=t1.dropoff_id AND t3.field='title' AND t3.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjMultiLang', "t4.model='pjLine' AND t4.foreign_id=t1.line_id AND t4.field='title' AND t4.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjMultiLang', "t5.model='pjLine' AND t5.foreign_id=t1.return_line_id AND t5.field='title' AND t5.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjClient', "t6.id=t1.client_id", 'left outer')
					->join('pjMultiLang', "t7.model='pjCountry' AND t7.foreign_id=t6.country_id AND t7.field='name' AND t7.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjMultiLang', "t8.model='pjLocation' AND t8.foreign_id=t1.location_id AND t8.field='address' AND t8.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjMultiLang', "t9.model='pjLocation' AND t9.foreign_id=t1.dropoff_id AND t9.field='address' AND t9.locale='".$this->getLocaleId()."'", 'left outer')
					->select("t1.*, t2.content as from_location, t3.content as to_location, t4.content as line, t5.content as return_line,
								t7.content as country, t8.content as from_address, t9.content as to_address,
								t6.title, t6.fname, t6.lname, t6.email,t6.phone, t6.company, t6.address, t6.city, t6.state, t6.zip")
					->find($_GET['id'])
					->getData();
					
				if (count($arr) === 0)
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionIndex&err=AB08");
				}
												 				
				$arr['data'] = pjAppController::getTokens($this->option_arr, $arr, PJ_SALT, $this->getLocaleId());
				
				$lang_message = pjMultiLangModel::factory()->select('t1.*')
											 ->where('t1.model','pjOption')
											 ->where('t1.locale', $this->getLocaleId())
											 ->where('t1.field', 'o_sms_confirmation_message')
											 ->limit(0, 1)
											 ->findAll()->getData();
					
				$this->set('arr', $arr);
				$this->set('lang_message', $lang_message[0]['content']);
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminBookings.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
}
?>