<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminBookings extends pjAdmin
{
	public $bookingExportOptions = 'pjCarPark_BookingExportOptions';
	
	private function pjActionCheck($uuid, $id=NULL)
	{
		$pjBookingModel = pjBookingModel::factory();
		if (!is_null($id))
		{
			$pjBookingModel->where('t1.id!=', $id);
		}
		if (0 == $pjBookingModel->where('t1.uuid', $uuid)->findCount()->getData())
		{
			return TRUE;
		}
		return FALSE;
	}
	
	public function pjActionCheckUniqueId()
	{
		$this->setAjax(true);
		if ($this->isXHR())
		{
			$get = $this->_get->raw();
			if (isset($get['uuid']) && pjValidation::pjActionNotEmpty($get['uuid']))
			{
				if (isset($get['id']) && (int) $get['id'] > 0)
				{
					echo ($this->pjActionCheck($get['uuid'], $get['id']) === TRUE) ? 'true' : 'false';
					exit;
				} else {
					echo ($this->pjActionCheck($get['uuid']) === TRUE) ? 'true' : 'false';
					exit;
				}
			}
			die('false');
		}
		exit;
	}
	
	public function pjActionGetBooking()
	{
		$this->checkLogin();
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjBookingModel = pjBookingModel::factory()
				->join('pjMultiLang', "t2.model='pjSpace' AND t2.foreign_id=t1.space_id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer');
			$get = $this->_get->raw();
			if (isset($get['q']) && !empty($get['q']))
			{
				$q = pjObject::escapeString($get['q']);
				$pjBookingModel->where('(t1.uuid LIKE "%'.$q.'%" OR t1.c_name LIKE "%'.$q.'%" OR t1.c_email LIKE "%'.$q.'%" OR t1.c_phone LIKE "%'.$q.'%")');
			}
						
			if (isset($get['space_id']) && (int) $get['space_id'] > 0)
			{
				$pjBookingModel->where('t1.space_id', $get['space_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']);
			}
			if (isset($get['date_from']) && !empty($get['date_from']) && isset($get['date_to']) && !empty($get['date_to']))
			{
				$df = pjDateTime::formatDate($get['date_from'], $this->option_arr['o_date_format']);
				$dt = pjDateTime::formatDate($get['date_to'], $this->option_arr['o_date_format']);
				$pjBookingModel->where("( (t1.from BETWEEN '$df' AND '$dt') OR (t1.to BETWEEN '$df' AND '$dt') OR ('$df' BETWEEN t1.from AND t1.to) OR ('$dt' BETWEEN t1.from AND t1.to) )");
			
			} else {
				if (isset($get['date_from']) && !empty($get['date_from']))
				{
					$df = pjDateTime::formatDate($get['date_from'], $this->option_arr['o_date_format']);
					$pjBookingModel->where("(t1.from >= '$df')");
				} elseif (isset($get['date_to']) && !empty($get['date_to'])) {
					$dt = pjDateTime::formatDate($get['date_to'], $this->option_arr['o_date_format']);
					$pjBookingModel->where("(t1.to <= '$dt')");
				}
			}
			
			if ($this->_get->toString('from'))
			{
			    $from = $this->_get->toString('from');
			    $pjBookingModel->where('DATE(t1.from)', pjDateTime::formatDate($from, $this->option_arr['o_date_format']));
			}
			if ($this->_get->toString('to'))
			{
			    $to = $this->_get->toString('to');
			    $pjBookingModel->where('DATE(t1.to)', pjDateTime::formatDate($to, $this->option_arr['o_date_format']));
			}
			
			$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 = $pjBookingModel
				->select("t1.*, t2.content as space")
				->orderBy("`$column` $direction")->limit($rowCount, $offset)->findAll()->getData();
			
			foreach($data as $k => $v)
			{
				$v['from'] = date($this->option_arr['o_date_format'], strtotime($v['from'])) . ', ' . date($this->option_arr['o_time_format'], strtotime($v['from'])) . ' - ' . date($this->option_arr['o_date_format'], strtotime($v['to'])) . ', ' . date($this->option_arr['o_time_format'], strtotime($v['to']));
				$v['c_name'] = pjSanitize::html($v['c_name']);
				$v['c_email'] = pjSanitize::html($v['c_email']);
				$v['space'] = pjSanitize::html($v['space']);
				unset($v['cc_exp_month']);
				unset($v['cc_exp_year']);
				$data[$k] = $v;
			}
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
	    if (!pjAuth::factory()->hasAccess())
	    {
	        $this->sendForbidden();
	        return;
	    }
	    
		if (!$this->_get->check('isExport')) {
			if (isset($_SESSION[$this->bookingExportOptions])) {
				unset($_SESSION[$this->bookingExportOptions]);
			}
		}
		$space_arr = pjSpaceModel::factory()
			->select('t1.*, t2.content as name')
			->join('pjMultiLang', "t2.model='pjSpace' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
			->where("t1.status", 'T')
			->orderBy("name ASC")
			->findAll()
			->getData();
		$this->set('space_arr', $space_arr);
		$this->set('date_format', pjUtil::toBootstrapDate($this->option_arr['o_date_format']));
		
		$this->appendCss('datepicker3.css', PJ_THIRD_PARTY_PATH . 'bootstrap_datepicker/');
		$this->appendJs('bootstrap-datepicker.js', PJ_THIRD_PARTY_PATH . 'bootstrap_datepicker/');		
		$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
		$this->appendJs('pjAdminBookings.js');
	}
	
	public function pjActionExportBookings()
	{
		$this->checkLogin();
	    if (!pjAuth::factory()->hasAccess())
	    {
	        $this->sendForbidden();
	        return;
	    }
		
		if ($this->_post->check('booking_export'))
		{
			$post = $this->_post->raw();
			$_SESSION[$this->bookingExportOptions] = $post;
			$pjBookingModel = pjBookingModel::factory();
			
			if($post['period'] == 'next')
			{
				$column = '`from`';
				$direction = 'ASC';

				$where_str = pjUtil::getComingWhere($post['coming_period'], $this->option_arr['o_week_start']);
				if($where_str != '')
				{
					$pjBookingModel->where($where_str);
				}
			}else{
				$column = 'created';
				$direction = 'ASC';
				$where_str = pjUtil::getMadeWhere($post['made_period'], $this->option_arr['o_week_start']);
				if($where_str != '')
				{
					$pjBookingModel->where($where_str);
				}
			}

			$arr= $pjBookingModel
				->select('t1.id, t1.space_id, t2.content AS space, t1.uuid, t1.from, t1.to, t1.status, t1.total,
						  t1.deposit, t1.c_name, t1.c_email, t1.c_phone, t1.c_notes, t1.c_address, t1.c_city, t1.c_country, t1.c_state, t1.c_zip, t1.ip, 
						  t1.payment_method, t1.created, t1.modified')
				->join('pjMultiLang', "t2.model='pjSpace' AND t2.foreign_id=t1.space_id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->orderBy("$column $direction")
				->findAll()
				->getData();
			if($post['type'] == 'file')
			{
				$this->setLayout('pjActionEmpty');
					
				if($post['format'] == 'csv')
				{
					$csv = new pjCSV();
					$csv->setHeader(true)->setName("Export-".time().".csv")->process($arr)->download();
				}
				if($post['format'] == 'xml')
				{
					$xml = new pjXML();
					$xml->setEncoding('UTF-8')->setName("Export-".time().".xml")->process($arr)->download();
				}
				if($post['format'] == 'ical')
				{
				    $ical_data = array();
				    foreach($arr as $k => $v)
				    {
				        $v['from'] = pjUtil::getDateTimeGMT($v['from'], $this->option_arr['o_timezone']);
				        $v['to'] = pjUtil::getDateTimeGMT($v['to'], $this->option_arr['o_timezone']);
				        $ical_data[$k] = $v;
				    }
					$ical = new pjICal();
					$ical
						->setName("Export-".time().".ics")
						->setProdID('Car Park Booking')
						->setSummary('c_name')
						->setDateFrom('from')
						->setDateTo('to')
						->setLocation('space')
						->process($ical_data)
						->download();
				}
				exit;
			} else {
				$pjPasswordModel = pjPasswordModel::factory();
				$password = md5($post['password'].PJ_SALT);
				$arr = $pjPasswordModel
					->where("t1.password", $password)
					->limit(1)
					->findAll()
					->getData();
				if (count($arr) != 1)
				{
					$pjPasswordModel->setAttributes(array('password' => $password))->insert();
				}
				$_SESSION[$this->bookingExportOptions]['raw_password'] = $post['password'];
				$_SESSION[$this->bookingExportOptions]['password'] = $password;
			}
		}else{
		    $this->appendJs('pjAdminBookings.js');
		}
	}
	
	public function pjActionExportBooking()
	{
		$this->checkLogin();
	    if (!pjAuth::factory()->hasAccess())
	    {
	        $this->sendForbidden();
	        return;
	    }
		
		$record = $this->_post->toArray('record');
		if (!empty($record))
		{
			$arr = pjBookingModel::factory()->whereIn('id', $record)->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Bookings-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionCreate()
	{
		$this->checkLogin();
	    if (!pjAuth::factory()->hasAccess())
	    {
	        $this->sendForbidden();
	        return;
	    }
		
		if ($this->_post->check('booking_create'))
		{
			$post = $this->_post->raw();
			if (!$this->pjActionCheck($post['uuid']))
			{
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminBookings&action=pjActionIndex&err=ABK09");
			}
			
			$data = array();
			
			$pjBookingModel = pjBookingModel::factory();
			$pjBookingExtraModel = pjBookingExtraModel::factory();
			
			$data['uuid'] = pjUtil::uuid();
			$data['ip']= pjUtil::getClientIp();
			$data['locale_id'] = $this->getLocaleId();
			$from_arr = pjUtil::convertDateTime($post['from'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
			$to_arr = pjUtil::convertDateTime($post['to'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
			
			unset($post['from']);
			unset($post['to']);
			
			$data['from'] = $from_arr['iso_date_time'];
			$data['to'] = $to_arr['iso_date_time'];
			
			$post = array_merge($post, $data);
			
			$id = $pjBookingModel->setAttributes($post)->insert()->getInsertId();
			if ($id !== false && (int) $id > 0)
			{
				if (isset($post['extra_id']) && is_array($post['extra_id']) && count($post['extra_id']) > 0)
				{
					$pjBookingExtraModel->begin();
					foreach ($post['extra_id'] as $k => $extra_id)
					{
						$cnt = 1;
						if($post['qty'][$k] != 'on')
						{
							$cnt = $post['qty'][$k];
						}
						$pjBookingExtraModel
							->reset()
							->set('booking_id', $id)
							->set('extra_id', $extra_id)
							->set('price', $post['price'][$k])
							->set('cnt', $cnt)
							->insert();
					}
					$pjBookingExtraModel->commit();
				}
				
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionIndex&err=AR03");
			} else {
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionIndex&err=AR04");
			}
		}else{
			
			$country_arr = pjBaseCountryModel::factory()
					->select('t1.id, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjBaseCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('t1.status', 'T')
					->orderBy('`name` ASC')->findAll()->getData();			
			$this->set('country_arr', $country_arr);
			$this->set('date_format', pjUtil::toBootstrapDate($this->option_arr['o_date_format']));
			
			$this->appendJs('moment-with-locales.min.js', PJ_THIRD_PARTY_PATH . 'moment/');
	        $this->appendCss('build/css/bootstrap-datetimepicker.min.css', PJ_THIRD_PARTY_PATH . 'bootstrap_datetimepicker/');
	        $this->appendJs('build/js/bootstrap-datetimepicker.min.js', PJ_THIRD_PARTY_PATH . 'bootstrap_datetimepicker/');
			$this->appendJs('pjAdminBookings.js');
		}
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
	    if (!pjAuth::factory()->hasAccess())
	    {
	        $this->sendForbidden();
	        return;
	    }
		
		$arr = pjBookingModel::factory()
			->find($_REQUEST['id'])
			->getData();
		
		if(count($arr) <= 0)
		{
			pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminBookings&action=pjActionIndex&err=AR08");
		}
	    
		if ($this->_post->check('booking_update'))
		{
			$post = $this->_post->raw();
			$data = array();			
			$pjBookingModel = pjBookingModel::factory();
			$pjBookingExtraModel = pjBookingExtraModel::factory();
			
			$from_arr = pjUtil::convertDateTime($post['from'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
			$to_arr = pjUtil::convertDateTime($post['to'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
			
			unset($post['from']);
			unset($post['to']);
			
			$data['from'] = $from_arr['iso_date_time'];
			$data['to'] = $to_arr['iso_date_time'];
			$data['modified'] = date('Y-m-d H:i:s');
			
			$post = array_merge($post, $data);
			$pjBookingModel->reset()->set('id', $post['id'])->modify($post);
			
			$pjBookingExtraModel->where('booking_id', $post['id'])->eraseAll();
			if (isset($post['extra_id']) && is_array($post['extra_id']) && count($post['extra_id']) > 0)
			{
				$pjBookingExtraModel->begin();
				foreach ($post['extra_id'] as $k => $extra_id)
				{
					$cnt = 1;
					if($post['qty'][$k] != 'on')
					{
						$cnt = $post['qty'][$k];
					}
					$pjBookingExtraModel
						->reset()
						->set('booking_id', $post['id'])
						->set('extra_id', $extra_id)
						->set('price', $post['price'][$k])
						->set('cnt', $cnt)
						->insert();
				}
				$pjBookingExtraModel->commit();
			}
			pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminBookings&action=pjActionUpdate&id=".$post['id']."&err=AR01");
		}else{
			$be_arr = pjBookingExtraModel::factory()
				->where('t1.booking_id', $arr['id'])
				->findAll()
				->getData();
			
			$country_arr = pjBaseCountryModel::factory()
					->select('t1.id, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjBaseCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('t1.status', 'T')
					->orderBy('`name` ASC')->findAll()->getData();			
			$this->set('country_arr', $country_arr);
			$this->set('date_format', pjUtil::toBootstrapDate($this->option_arr['o_date_format']));

			$from_ts = strtotime($arr['from']);
			$to_ts = strtotime($arr['to']);

			$iso_from = date('Y-m-d', $from_ts);
			$iso_to = date('Y-m-d', $to_ts);

			$from = date($this->option_arr['o_date_format'], $from_ts) . ' ' . date($this->option_arr['o_time_format'], $from_ts);
			$to = date($this->option_arr['o_date_format'], $to_ts) . ' ' . date($this->option_arr['o_time_format'], $to_ts);

			$rental_days = pjAppController::getRentalDays($this->option_arr, $iso_from, $iso_to, date('H', $from_ts), date('H', $to_ts), date('i', $from_ts), date('i', $to_ts));
			$space_arr = pjAppController::getSpaces($from_ts, $to_ts, $iso_from, $iso_to, $rental_days, $this->getLocaleId(), null, $arr['id']);
			$extra_arr = pjAppController::getExtras($iso_from, $iso_to, $this->getLocaleId(),  $arr['id']);

			$code_arr = array();
			if (pjObject::getPlugin('pjVouchers') !== NULL)
            {
                $result = pjVoucherModel::factory()->getVoucher($arr['discount_code'], $iso_from, date('H:i:s', $from_ts));
                if($result['status'] == 'OK')
                {
                    $code_arr = $result['arr'];
                }
            }
			
			$this->set('arr', $arr);
			$this->set('be_arr', $be_arr);
			$this->set('country_arr', $country_arr);
			$this->set('from', $from);
			$this->set('to', $to);
			$this->set('rental_days', $rental_days);
			$this->set('space_arr', $space_arr);
			$this->set('extra_arr', $extra_arr);
			$this->set('code_arr', $code_arr);

			$this->appendJs('tinymce.min.js', PJ_THIRD_PARTY_PATH . 'tinymce/');
			$this->appendJs('moment-with-locales.min.js', PJ_THIRD_PARTY_PATH . 'moment/');
	        $this->appendCss('build/css/bootstrap-datetimepicker.min.css', PJ_THIRD_PARTY_PATH . 'bootstrap_datetimepicker/');
	        $this->appendJs('build/js/bootstrap-datetimepicker.min.js', PJ_THIRD_PARTY_PATH . 'bootstrap_datetimepicker/');
			$this->appendJs('pjAdminBookings.js');
		}
	}
	
	public function pjActionPrint()
	{
		$this->checkLogin();
	    if (!pjAuth::factory()->hasAccess())
	    {
	        $this->sendForbidden();
	        return;
	    }
	
		$this->setLayout('pjActionPrint');
		
		$arr = pjBookingModel::factory()
			->find($_REQUEST['id'])
			->getData();
		
		if(count($arr) <= 0)
		{
			pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminBookings&action=pjActionIndex&err=AR08");
		}
		$space_arr = pjSpaceModel::factory()
			->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjSpace' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
			->select('t1.*, t2.content as name')
			->find($arr['space_id'])
			->getData();
		$space = $space_arr['name'];
		
		$be_arr = pjBookingExtraModel::factory()
			->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjExtra' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
			->join('pjExtra', "t3.id=t1.extra_id", 'left')
			->select('t1.*, t2.content as name, t3.per, t3.price as unit_price')
			->where('t1.booking_id', $arr['id'])
			->findAll()
			->getData();
		$extra_arr = array();
		$extra_per = __('extra_per', true);
		foreach($be_arr as $k => $v)
		{
			$extra_arr[] = $v['name'] . ' (' . pjCurrency::formatPrice($v['unit_price']) . ' ' . $extra_per[$v['per']] .  ') x ' . $v['cnt'] . ' = ' . pjCurrency::formatPrice($v['price']);
		}
		$extras = join("<br/>", $extra_arr);
		
		$country = NULL;
		if(isset($arr['c_country']) && (int) $arr['c_country'] > 0)
		{
			$country_arr = pjBaseCountryModel::factory()
            ->select('t1.id, t2.content AS country_title')
            ->join('pjBaseMultiLang', "t2.model='pjBaseCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
            ->find($arr['c_country'])->getData();
            if (!empty($country_arr))
            {
                $country = $country_arr['country_title'];
            }
		}
		
		$this->set('arr', $arr);
		$this->set('space', $space);
		$this->set('extras', $extras);
		$this->set('country', $country);
	}
	
	public function pjActionGetSpaces()
	{
		$this->checkLogin();
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$post = $this->_post->raw();
			$booking_id = null;
			if(isset($post['id']))
			{
				$booking_id = $post['id'];
			}
			
			$from_arr = pjUtil::convertDateTime($post['from'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
			$to_arr = pjUtil::convertDateTime($post['to'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
			
			$from_ts = $from_arr['ts'];
			$to_ts = $to_arr['ts'];
			
			$rental_days = pjAppController::getRentalDays($this->option_arr, $from_arr['iso_date'], $to_arr['iso_date'], date('H', $from_ts), date('H', $to_ts), date('i', $from_ts), date('i', $to_ts));
			$space_arr = pjAppController::getSpaces($from_ts, $to_ts, $from_arr['iso_date'], $to_arr['iso_date'], $rental_days, $this->getLocaleId(), null, $booking_id);
			$extra_arr = pjAppController::getExtras($from_arr['iso_date'], $to_arr['iso_date'], $this->getLocaleId(), $booking_id);
			
			$this->set('rental_days', $rental_days);
			$this->set('space_arr', $space_arr);
			$this->set('extra_arr', $extra_arr);
		}
	}
	
	public function pjActionApplyCode()
	{
		$this->setAjax(true);
		
		if ($this->isXHR())
		{
			$response = array();
			$code_arr = array();
			$post = $this->_post->raw();
			if((int) $post['space_id'] > 0 && !empty($post['from']) && !empty($post['to']))
			{
				$from_arr = pjUtil::convertDateTime($post['from'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
				if (pjObject::getPlugin('pjVouchers') !== NULL)
				{
					$result = pjVoucherModel::factory()->getVoucher($post['discount_code'], $from_arr['iso_date'], date("H:i:s", $from_arr['ts']));
					if($result['status'] == 'OK')
	                {
	                    $code_arr = $result['arr'];
	                }
				}
			}
			$response['code'] = 200;
			if(empty($code_arr))
			{
				$response['code'] = 100;
			}
			$response['arr'] = $code_arr;
			pjAppController::jsonResponse($response);
		}
	}
	
	public function pjActionDeleteBooking()
	{
		$this->setAjax(true);
	
		if (!pjAuth::factory()->hasAccess())
		{
		    self::jsonResponse(array('status' => 'ERR', 'code' => 103, 'text' => 'Access denied.'));
		}
		
		if (!$this->isXHR())
		{
		    self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		if (!self::isGet() && !$this->_get->check('id') && $this->_get->toInt('id') < 0)
		{
		    self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'HTTP method not allowed.'));
		}
		if ($this->_get->toInt('id') > 0) {
			$id = $this->_get->toInt('id');
			$pjBookingModel = pjBookingModel::factory();
			if ($pjBookingModel->setAttributes(array('id' => $id))->erase()->getAffectedRows() == 1)
			{
				pjBookingPaymentModel::factory()->where('booking_id', $id)->eraseAll();
				pjBookingExtraModel::factory()->where('booking_id', $id)->eraseAll();
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Booking has been deleted.'));
			} else {
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Booking has not been deleted.'));
			}
		} else {
			pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Missing or empty parameters.'));
		}
		exit;
	}
	
	public function pjActionDeleteBookingBulk()
	{
		$this->setAjax(true);
	
		if (!pjAuth::factory()->hasAccess())
		{
		    self::jsonResponse(array('status' => 'ERR', 'code' => 103, 'text' => 'Access denied.'));
		}
		if (!$this->isXHR())
		{
		    self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		if (!self::isPost())
		{
		    self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'HTTP method not allowed.'));
		}
	
		$record = $this->_post->toArray('record');		
		if (!empty($record))
		{
			$pjBookingModel = pjBookingModel::factory();
			
			$pjBookingModel->reset()->whereIn('id', $record)->eraseAll();
			pjBookingPaymentModel::factory()->whereIn('booking_id', $record)->eraseAll();
			pjBookingExtraModel::factory()->whereIn('booking_id', $record)->eraseAll();
			self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Booking(s) has been deleted.'));
		}
		self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing or empty parameters.'));
		exit;
	}
	
	public function pjActionSaveBooking()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$get = $this->_get->raw();
			$post = $this->_post->raw();
			pjBookingModel::factory()->where('id', $get['id'])->limit(1)->modifyAll(array($post['column'] => $post['value']));
		}
		exit;
	}
	
	public function pjActionExportFeed()
	{
		$this->setLayout('pjActionEmpty');
		$access = true;
		$get = $this->_get->raw();
		if(isset($get['p']))
		{
			$pjPasswordModel = pjPasswordModel::factory();
			$arr = $pjPasswordModel->where('t1.password', $get['p'])->limit(1)->findAll()->getData();
			if (count($arr) != 1)
			{
				$access = false;
			}
		}else{
			$access = false;
		}
		if($access == true)
		{
			$arr = pjSanitize::clean($this->pjGetFeedData($get));
			if(!empty($arr))
			{
				if($get['format'] == 'xml')
				{
					$xml = new pjXML();
					echo $xml->setEncoding('UTF-8')->process($arr)->getData();
						
				}
				if($get['format'] == 'csv')
				{
					$csv = new pjCSV();
					echo $csv->setHeader(true)->process($arr)->getData();
						
				}
				if($get['format'] == 'ical')
				{
				    $ical_data = array();
				    foreach($arr as $k => $v)
				    {
				        $v['from'] = pjUtil::getDateTimeGMT($v['from'], $this->option_arr['o_timezone']);
				        $v['to'] = pjUtil::getDateTimeGMT($v['to'], $this->option_arr['o_timezone']);
				        $ical_data[$k] = $v;
				    }
					$ical = new pjICal();
					echo $ical
						->setProdID('Car Park Booking')
						->setSummary('c_name')
						->setDateFrom('from')
						->setDateTo('to')
						->setLocation('space')
						->process($ical_data)
						->getData();
						
				}
			}
		}else{
			__('lblNoAccessToFeed');
		}
		exit;
	}
	public function pjGetFeedData($get)
	{
		$arr = array();
		$status = true;
		$type = '';
		$period = '';
		if(isset($get['period']))
		{
			if(!ctype_digit($get['period']))
			{
				$status = false;
			}else{
				$period = $get['period'];
			}
		}else{
			$status = false;
		}
		if(isset($get['type']))
		{
			if(!ctype_digit($get['type']))
			{
				$status = false;
			}else{
				$type = $get['type'];
			}
		}else{
			$status = false;
		}
		if($status == true && $type != '' && $period != '')
		{
			$pjBookingModel = pjBookingModel::factory();
			
			if($type == '1')
			{
				$column = '`from`';
				$direction = 'ASC';
					
				$where_str = pjUtil::getComingWhere($period, $this->option_arr['o_week_start']);
				if($where_str != '')
				{
					$pjBookingModel->where($where_str);
				}
			}else{
				$column = 'created';
				$direction = 'DESC';
				$where_str = pjUtil::getMadeWhere($period, $this->option_arr['o_week_start']);
				if($where_str != '')
				{
					$pjBookingModel->where($where_str);
				}
			}
			$arr = $pjBookingModel
				->select('t1.id, t1.space_id, t2.content AS space, t1.uuid, t1.from, t1.to, t1.status, t1.total,
							  t1.deposit, t1.c_name, t1.c_email, t1.c_phone, t1.c_notes, t1.c_address, t1.c_city, t1.c_country, t1.c_state, t1.c_zip, t1.ip, 
							  t1.payment_method, t1.created, t1.modified')
			  	->join('pjMultiLang', "t2.model='pjSapce' AND t2.foreign_id=t1.space_id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
			  	->orderBy("$column $direction")
			  	->findAll()
			  	->getData();
		}
		return $arr;
	}
	
	public function pjActionCheckTime()
	{
		$this->checkLogin();
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
		    $post = $this->_post->raw();
		    
		    $from_arr = pjUtil::convertDateTime($post['from'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
			$to_arr = pjUtil::convertDateTime($post['to'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
			
			$from_ts = $from_arr['ts'];
			$to_ts = $to_arr['ts'];
			if ($from_ts > $to_ts) {
				pjAppController::jsonResponse(array('status' => 'ERR', 'rental_days' => 0));
			} else {
				$rental_days = pjAppController::getRentalDays($this->option_arr, $from_arr['iso_date'], $to_arr['iso_date'], date('H', $from_ts), date('H', $to_ts), date('i', $from_ts), date('i', $to_ts));
				pjAppController::jsonResponse(array('status' => 'OK', 'rental_days' => $rental_days));
			}
		}
		exit;
	}
	
	public function pjActionConfirmation()
	{
		$this->checkLogin();
	    $this->setAjax(true);
	    
	    if ($this->isXHR())
	    {
	        if (self::isPost())
	        {
	            if($this->_post->toInt('send_email') && $this->_post->toString('to') && $this->_post->toString('subject') && $this->_post->toString('message') && $this->_post->toInt('id'))
	            {
	                $Email = self::getMailer($this->option_arr);
	                $r = $Email
	                ->setTo($this->_post->toString('to'))
	                ->setSubject($this->_post->toString('subject'))
	                ->send($this->_post->toString('message'));
	                if (isset($r) && $r)
	                {
	                    pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
	                }
	                pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
	            }
	        }
	        if (self::isGet())
	        {
	            if($booking_id = $this->_get->toInt('booking_id'))
	            {
	            	$pjNotificationModel = pjNotificationModel::factory();
	               	$arr = pjBookingModel::factory()
						->find($booking_id)
						->getData();
					$arr['calendar_id'] = $this->getForeignId();
					$locale_id = (int)$arr['locale_id'] > 0 ? (int)$arr['locale_id'] : $this->getLocaleId();
					$tokens = pjAppController::getTokens($arr, $this->option_arr, PJ_SALT, $locale_id);
					
					$notification = $pjNotificationModel->reset()->where('recipient', 'client')->where('transport', 'email')->where('variant', 'confirmation')->findAll()->getDataIndex(0);
					if((int) $notification['id'] > 0 && $notification['is_active'] == 1)
					{
					    $resp = pjFront::pjActionGetSubjectMessage($notification, $locale_id, $this->getForeignId());
					    $lang_message = $resp['lang_message'];
					    $lang_subject = $resp['lang_subject'];
					   
					    $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(
					        'id' => $booking_id,
					        'to' => $arr['c_email'],
					        'message' => $message_client,
					        'subject' => $subject_client
					    ));
					}
					
	            }
	        }
	    }
	}
}
?>