<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminDiscounts extends pjAdmin
{
	/* Free Nights */
	public function pjActionFrees()
	{
	    $this->checkLogin();
	    if (!pjAuth::factory()->hasAccess())
	    {
	        $this->sendForbidden();
	        return;
	    }
		if (self::isGet())
		{
			$room_arr = pjRoomModel::factory()
				->select('t1.*, t2.content AS name')
				->join('pjMultiLang', "t2.model='pjRoom' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->where('t1.calendar_id', $this->getForeignId())
				->orderBy('`name` ASC')
				->findAll()
				->getData();
			
			$rooms = array();
			foreach ($room_arr as $room)
			{
				$rooms[] = array(
					'value' => $room['id'],
					'label' => pjSanitize::clean($room['name'])
				);
			}
			$this->set('rooms', pjAppController::jsonEncode($rooms));
			$this->set('date_format', pjUtil::toBootstrapDate($this->option_arr['o_date_format']));
				
			$this->set('room_arr', pjRoomModel::factory()
				->select('t1.*, t2.content AS name')
				->join('pjMultiLang', "t2.model='pjRoom' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->where('t1.calendar_id', $this->getForeignId())
				->orderBy('`name` ASC')
				->findAll()
				->getData()
			);
			
			$this->appendCss('datepicker.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('pjAdminDiscounts.js');
		}
	}
	
	public function pjActionGetFrees()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		$pjDiscountFreeModel = pjDiscountFreeModel::factory();
			
		$column = 'date_from';
		$direction = 'ASC';
		if ($this->_get->toString('column') && in_array(strtoupper($this->_get->toString('direction')), array('ASC', 'DESC')))
		{
			$column = $this->_get->toString('column');
			$direction = strtoupper($this->_get->toString('direction'));
		}

		$total = $pjDiscountFreeModel->findCount()->getData();
		$rowCount = $this->_get->toInt('rowCount') ? $this->_get->toInt('rowCount') : 10;
		$pages = ceil($total / $rowCount);
		$page = $this->_get->toInt('page') ? $this->_get->toInt('page') : 1;
		$offset = ((int) $page - 1) * $rowCount;
		if ($page > $pages)
		{
			$page = $pages;
		}

		$data = $pjDiscountFreeModel
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();
		foreach ($data as $k => $v) {
			$data[$k]['date_from_formated'] = date($this->option_arr['o_date_format'], strtotime($v['date_from']));
			$data[$k]['date_to_formated'] = date($this->option_arr['o_date_format'], strtotime($v['date_to']));
		}	
		self::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
	}
	
	public function pjActionAddFree()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
			
		if (self::isPost() && $this->_post->check('add_free'))
		{
			$data = array();
			$data['date_from'] = pjDateTime::formatDate($this->_post->toString('date_from'), $this->option_arr['o_date_format']);
			$data['date_to'] = pjDateTime::formatDate($this->_post->toString('date_to'), $this->option_arr['o_date_format']);
			$id = pjDiscountFreeModel::factory(array_merge($this->_post->raw(), $data))->insert()->getInsertId();
			if ($id !== false && (int) $id > 0)
			{
				self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
			}
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
		}
		
		if (self::isGet())
		{
			$this->set('room_arr', pjRoomModel::factory()
					->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjRoom' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('t1.calendar_id', $this->getForeignId())
					->orderBy('`name` ASC')
					->findAll()
					->getData()
			);
		}
	}
	
	public function pjActionDeleteFree()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
			
		if (pjDiscountFreeModel::factory()->set('id', $this->_get->toInt('id'))->erase()->getAffectedRows() == 1)
		{
			$response = array('status' => 'OK', 'code' => 200, 'text' => '');
		} else {
			$response = array('status' => 'ERR', 'code' => 100, 'text' => '');
		}
		self::jsonResponse($response);
	}
	
	public function pjActionDeleteFreeBulk()
	{
		$this->setAjax(true);
	
		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.'));
		}

		if (!$this->_post->has('record') || !($record = $this->_post->toArray('record')))
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Missing, empty or invalid data.'));
		}
		
		if (pjDiscountFreeModel::factory()->whereIn('id', $record)->eraseAll()->getAffectedRows() > 0)
		{
			self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
		}
		self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
	}
	
	public function pjActionUpdateFree()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		$pjDiscountFreeModel = pjDiscountFreeModel::factory();
		if (self::isPost() && $this->_post->check('update_free'))
		{
			$id = $this->_post->toInt('id');
			$arr = $pjDiscountFreeModel->find($id)->getData();
			$data = array();
			$data['date_from'] = pjDateTime::formatDate($this->_post->toString('date_from'), $this->option_arr['o_date_format']);
			$data['date_to'] = pjDateTime::formatDate($this->_post->toString('date_to'), $this->option_arr['o_date_format']);
			if ($arr) {
				$pjDiscountFreeModel->reset()->set('id', $this->_post->toInt('id'))->modify(array_merge($this->_post->raw(), $data));
			} else {
				$pjDiscountFreeModel->reset()->setAttributes(array_merge($this->_post->raw(), $data))->insert();
			}
			self::jsonResponse(array('status' => 'OK'));
		}
		
		if (self::isGet())
		{
			$arr = $pjDiscountFreeModel->find($this->_get->toInt('id'))->getData();
			$this->set('arr', $arr);
			$this->set('room_arr', pjRoomModel::factory()
					->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjRoom' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('t1.calendar_id', $this->getForeignId())
					->orderBy('`name` ASC')
					->findAll()
					->getData()
			);
		}
	}
	
	public function pjActionSaveFree()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		if (!self::isPost())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'HTTP method not allowed.'));
		}
		
		$params = array(
				'id' => $this->_get->toInt('id'),
				'column' => $this->_post->toString('column'),
				'value' => $this->_post->toString('value'),
		);
		
		if (!(isset($params['id'], $params['column'], $params['value'])
				&& pjValidation::pjActionNumeric($params['id'])
				&& pjValidation::pjActionNotEmpty($params['column'])))
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Missing, empty or invalid parameters.'));
		}
		
		$pjDiscountFreeModel = pjDiscountFreeModel::factory();
		if (!in_array($params['column'], $pjDiscountFreeModel->getI18n()))
		{
			$record = $pjDiscountFreeModel->find($params['id'])->getData();
			if (in_array($params['column'], array('date_from', 'date_to')))
			{
				$params['value'] = pjDateTime::formatDate($params['value'], $this->option_arr['o_date_format']);
				
				if ($params['column'] == 'date_from')
				{
					$date_from = $params['value'];
					$date_to = $record['date_to'];
				} elseif ($params['column'] == 'date_to') {
					$date_from = $record['date_from'];
					$date_to = $params['value'];
				}

				if (strtotime($date_from) > strtotime($date_to))
				{
					self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Invalid date range'));
				}
			}
			if (in_array($params['column'], array('min_nights', 'max_nights', 'free_nights')))
			{
				if (!is_numeric($params['value']) || (int) $params['value'] < 0 || (int) $params['value'] > 255)
				{
					self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Value out of range'));
				}
			}
			$pjDiscountFreeModel->set('id', $this->_get->toInt('id'))->modify(array($params['column'] => $params['value']));
		} else {
			pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($params['column'] => $params['value'])), $this->_get->toInt('id'), 'pjDiscountFree');
		}
		self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
	}
	/* End Free Nights */
	
	/* Promo Code */
	public function pjActionCodes()
	{
		if (self::isGet())
		{
			$room_arr = pjRoomModel::factory()
				->select('t1.*, t2.content AS name')
				->join('pjMultiLang', "t2.model='pjRoom' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->where('t1.calendar_id', $this->getForeignId())
				->orderBy('`name` ASC')
				->findAll()
				->getData();
			
			$rooms = array();
			foreach ($room_arr as $room)
			{
				$rooms[] = array(
					'value' => $room['id'],
					'label' => pjSanitize::clean($room['name'])
				);
			}
			$this->set('rooms', pjAppController::jsonEncode($rooms));
			$this->set('date_format', pjUtil::toBootstrapDate($this->option_arr['o_date_format']));
				
			$this->set('room_arr', pjRoomModel::factory()
				->select('t1.*, t2.content AS name')
				->join('pjMultiLang', "t2.model='pjRoom' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->where('t1.calendar_id', $this->getForeignId())
				->orderBy('`name` ASC')
				->findAll()
				->getData()
			);
				
			$types = array();
			foreach (__('discount_types', true) as $k => $v)
			{
				$types[] = array(
					'value' => $k,
					'label' =>$v
				);
			}
			$this->set('types', pjAppController::jsonEncode($types));
			
			$this->appendCss('datepicker.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('pjAdminDiscounts.js');
		}
	}
	
	public function pjActionGetCodes()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		$pjDiscountCodeModel = pjDiscountCodeModel::factory();
			
		$column = 'date_from';
		$direction = 'ASC';
		if ($this->_get->toString('column') && in_array(strtoupper($this->_get->toString('direction')), array('ASC', 'DESC')))
		{
			$column = $this->_get->toString('column');
			$direction = strtoupper($this->_get->toString('direction'));
		}

		$total = $pjDiscountCodeModel->findCount()->getData();
		$rowCount = $this->_get->toInt('rowCount') ? $this->_get->toInt('rowCount') : 10;
		$pages = ceil($total / $rowCount);
		$page = $this->_get->toInt('page') ? $this->_get->toInt('page') : 1;
		$offset = ((int) $page - 1) * $rowCount;
		if ($page > $pages)
		{
			$page = $pages;
		}

		$data = $pjDiscountCodeModel
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();
		foreach ($data as $k => $v) {
			$data[$k]['promo_code'] = pjSanitize::clean($v['promo_code']);
			$data[$k]['date_from_formated'] = date($this->option_arr['o_date_format'], strtotime($v['date_from']));
			$data[$k]['date_to_formated'] = date($this->option_arr['o_date_format'], strtotime($v['date_to']));
		}		
		
		self::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
	}
	
	public function pjActionAddCode()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		if (self::isPost() && $this->_post->check('add_code'))
		{
			$pjDiscountCodeModel = pjDiscountCodeModel::factory();
			
			$cnt = $pjDiscountCodeModel->where('t1.room_id', $this->_post->toInt('room_id'))->where('t1.promo_code', $this->_post->toString('promo_code'))->findCount()->getData();
			if ($cnt > 0) {
				self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
			} else {
				$data = array();
				$data['date_from'] = pjDateTime::formatDate($this->_post->toString('date_from'), $this->option_arr['o_date_format']);
				$data['date_to'] = pjDateTime::formatDate($this->_post->toString('date_to'), $this->option_arr['o_date_format']);
				$id = $pjDiscountCodeModel->reset()->setAttributes(array_merge($this->_post->raw(), $data))->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
				}
				self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
			}
		}
		
		if (self::isGet())
		{
			$this->set('room_arr', pjRoomModel::factory()
					->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjRoom' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('t1.calendar_id', $this->getForeignId())
					->orderBy('`name` ASC')
					->findAll()
					->getData()
			);
		}
	}
	
	public function pjActionDeleteCode()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		if (pjDiscountCodeModel::factory()->set('id', $this->_get->toInt('id'))->erase()->getAffectedRows() == 1)
		{
			$response = array('status' => 'OK', 'code' => 200, 'text' => '');
		} else {
			$response = array('status' => 'ERR', 'code' => 100, 'text' => '');
		}
		self::jsonResponse($response);
	}
	
	public function pjActionDeleteCodeBulk()
	{
		$this->setAjax(true);
	
		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.'));
		}

		if (!$this->_post->has('record') || !($record = $this->_post->toArray('record')))
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Missing, empty or invalid data.'));
		}
		
		if (pjDiscountCodeModel::factory()->whereIn('id', $record)->eraseAll()->getAffectedRows() > 0)
		{
			self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
		}
		self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
	}
	
	public function pjActionUpdateCode()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		$pjDiscountCodeModel = pjDiscountCodeModel::factory();
		if (self::isPost() && $this->_post->check('update_code'))
		{
			$id = $this->_post->toInt('id');
			$arr = $pjDiscountCodeModel->find($id)->getData();
			$data = array();
			$data['date_from'] = pjDateTime::formatDate($this->_post->toString('date_from'), $this->option_arr['o_date_format']);
			$data['date_to'] = pjDateTime::formatDate($this->_post->toString('date_to'), $this->option_arr['o_date_format']);
			if ($arr) {
				$cnt = $pjDiscountCodeModel->reset()->where('t1.id <>', $id)->where('t1.room_id', $this->_post->toInt('room_id'))->where('t1.promo_code', $this->_post->toString('promo_code'))->findCount()->getData();
				if ($cnt > 0) {
					self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
				} else {
					$pjDiscountCodeModel->reset()->set('id', $this->_post->toInt('id'))->modify(array_merge($this->_post->raw(), $data));
				}
			} else {
				$cnt = $pjDiscountCodeModel->reset()->where('t1.room_id', $this->_post->toInt('room_id'))->where('t1.promo_code', $this->_post->toString('promo_code'))->findCount()->getData();
				if ($cnt > 0) {
					self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
				} else {
					$pjDiscountCodeModel->reset()->setAttributes(array_merge($this->_post->raw(), $data))->insert();
				}
			}
			self::jsonResponse(array('status' => 'OK'));
		}
		
		if (self::isGet())
		{
			$arr = $pjDiscountCodeModel->find($this->_get->toInt('id'))->getData();
			$this->set('arr', $arr);
			$this->set('room_arr', pjRoomModel::factory()
					->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjRoom' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('t1.calendar_id', $this->getForeignId())
					->orderBy('`name` ASC')
					->findAll()
					->getData()
			);
		}
	}
	
	public function pjActionSaveCode()
	{
	$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		if (!self::isPost())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'HTTP method not allowed.'));
		}
		
		$params = array(
				'id' => $this->_get->toInt('id'),
				'column' => $this->_post->toString('column'),
				'value' => $this->_post->toString('value'),
		);
		
		$pjDiscountCodeModel = pjDiscountCodeModel::factory();
		if (!in_array($params['column'], $pjDiscountCodeModel->getI18n()))
		{
			$record = $pjDiscountCodeModel->find($this->_get->toInt('id'))->getData();
			if (in_array($params['column'], array('date_from', 'date_to')))
			{
				$params['value'] = pjDateTime::formatDate($params['value'], $this->option_arr['o_date_format']);
				
				if ($params['column'] == 'date_from')
				{
					$date_from = $params['value'];
					$date_to = $record['date_to'];
				} elseif ($params['column'] == 'date_to') {
					$date_from = $record['date_from'];
					$date_to = $params['value'];
				}

				if (strtotime($date_from) > strtotime($date_to))
				{
					self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Invalid date range'));
				}
			}
			$pjDiscountCodeModel->set('id', $this->_get->toInt('id'))->modify(array($params['column'] => $params['value']));
		} else {
			pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($params['column'] => $params['value'])), $this->_get->toInt('id'), 'pjDiscountCode');
		}
		self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
	}
	/* End Promo Code */
	
	/* Packages */
	public function pjActionPackages()
	{
	    $this->checkLogin();
	    if (!pjAuth::factory()->hasAccess())
	    {
	        $this->sendForbidden();
	        return;
	    }
		if (self::isGet())
		{
			$room_arr = pjRoomModel::factory()
				->select('t1.*, t2.content AS name')
				->join('pjMultiLang', "t2.model='pjRoom' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->where('t1.calendar_id', $this->getForeignId())
				->orderBy('`name` ASC')
				->findAll()
				->getData();
			
			$rooms = array();
			foreach ($room_arr as $room)
			{
				$rooms[] = array(
					'value' => $room['id'],
					'label' => pjSanitize::clean($room['name'])
				);
			}
			$this->set('rooms', self::jsonEncode($rooms));
			$this->set('date_format', pjUtil::toBootstrapDate($this->option_arr['o_date_format']));
				
			$this->set('room_arr', pjRoomModel::factory()
				->select('t1.*, t2.content AS name')
				->join('pjMultiLang', "t2.model='pjRoom' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->where('t1.calendar_id', $this->getForeignId())
				->orderBy('`name` ASC')
				->findAll()
				->getData()
			);
				
			$days = array();
			foreach (__('days', true) as $k => $v)
			{
				$days[] = array(
					'value' => $k,
					'label' =>$v
				);
			}
			$this->set('days', self::jsonEncode($days));
			
			$this->appendCss('datepicker.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('pjAdminDiscounts.js');
		}
	}
	
	public function pjActionGetPackages()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		$pjDiscountPackageModel = pjDiscountPackageModel::factory();
			
		$column = 'date_from';
		$direction = 'ASC';
		if ($this->_get->toString('column') && in_array(strtoupper($this->_get->toString('direction')), array('ASC', 'DESC')))
		{
			$column = $this->_get->toString('column');
			$direction = strtoupper($this->_get->toString('direction'));
		}

		$total = $pjDiscountPackageModel->findCount()->getData();
		$rowCount = $this->_get->toInt('rowCount') ? $this->_get->toInt('rowCount') : 10;
		$pages = ceil($total / $rowCount);
		$page = $this->_get->toInt('page') ? $this->_get->toInt('page') : 1;
		$offset = ((int) $page - 1) * $rowCount;
		if ($page > $pages)
		{
			$page = $pages;
		}

		$data = $pjDiscountPackageModel
					->orderBy("$column $direction")
					->limit($rowCount, $offset)
					->findAll()
					->getData();
		foreach ($data as $k => $v) {
			$data[$k]['date_from_formated'] = date($this->option_arr['o_date_format'], strtotime($v['date_from']));
			$data[$k]['date_to_formated'] = date($this->option_arr['o_date_format'], strtotime($v['date_to']));
		}
		
		self::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
	}
	
	public function pjActionAddPackage()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
			
		if (self::isPost() && $this->_post->check('add_package'))
		{
			$data = array();
			$data['date_from'] = pjDateTime::formatDate($this->_post->toString('date_from'), $this->option_arr['o_date_format']);
			$data['date_to'] = pjDateTime::formatDate($this->_post->toString('date_to'), $this->option_arr['o_date_format']);
			$id = pjDiscountPackageModel::factory(array_merge($this->_post->raw(), $data))->insert()->getInsertId();
			if ($id !== false && (int) $id > 0)
			{
				self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
			}
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
		}
		
		if (self::isGet())
		{
			$this->set('room_arr', pjRoomModel::factory()
					->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjRoom' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('t1.calendar_id', $this->getForeignId())
					->orderBy('`name` ASC')
					->findAll()
					->getData()
			);
		}
	}
	
	public function pjActionUpdatePackage()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		$pjDiscountPackageModel = pjDiscountPackageModel::factory();
		
		if (self::isPost() && $this->_post->check('update_package'))
		{
			$id = $this->_post->toInt('id');
			$arr = $pjDiscountPackageModel->find($id)->getData();
			$data = array();
			$data['date_from'] = pjDateTime::formatDate($this->_post->toString('date_from'), $this->option_arr['o_date_format']);
			$data['date_to'] = pjDateTime::formatDate($this->_post->toString('date_to'), $this->option_arr['o_date_format']);
			if ($arr) {
				$pjDiscountPackageModel->reset()->set('id', $this->_post->toInt('id'))->modify(array_merge($this->_post->raw(), $data));
			} else {
				$pjDiscountPackageModel->reset()->setAttributes(array_merge($this->_post->raw(), $data))->insert();
			}
			self::jsonResponse(array('status' => 'OK'));
		}
		
		if (self::isGet())
		{
			$arr = $pjDiscountPackageModel->find($this->_get->toInt('id'))->getData();
			$this->set('arr', $arr);
			
			$this->set('room_arr', pjRoomModel::factory()
					->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjRoom' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('t1.calendar_id', $this->getForeignId())
					->orderBy('`name` ASC')
					->findAll()
					->getData()
			);
		}
	}
	
	public function pjActionSavePackage()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		if (!self::isPost())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'HTTP method not allowed.'));
		}
		
		$params = array(
				'id' => $this->_get->toInt('id'),
				'column' => $this->_post->toString('column'),
				'value' => $this->_post->toString('value'),
		);
		if (!(isset($params['id'], $params['column'], $params['value'])
				&& pjValidation::pjActionNumeric($params['id'])
				&& pjValidation::pjActionNotEmpty($params['column'])))
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Missing, empty or invalid parameters.'));
		}
		
		$pjDiscountPackageModel = pjDiscountPackageModel::factory();
		if (!in_array($params['column'], $pjDiscountPackageModel->getI18n()))
		{
			$record = $pjDiscountPackageModel->find($this->_get->toInt('id'))->getData();
			if (in_array($params['column'], array('date_from', 'date_to')))
			{
				$params['value'] = pjDateTime::formatDate($params['value'], $this->option_arr['o_date_format']);
				
				if ($params['column'] == 'date_from')
				{
					$date_from = $params['value'];
					$date_to = $record['date_to'];
				} elseif ($params['column'] == 'date_to') {
					$date_from = $record['date_from'];
					$date_to = $params['value'];
				}

				if (strtotime($date_from) > strtotime($date_to))
				{
					self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Invalid date range'));
				}
			}
			if (in_array($params['column'], array('start_day', 'end_day')))
			{
				if (!is_numeric($params['value']) || (int) $params['value'] < 0 || (int) $params['value'] > 6)
				{
					self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Value out of range'));
				}
			}
			$pjDiscountPackageModel->set('id', $this->_get->toInt('id'))->modify(array($params['column'] => $params['value']));
		} else {
			pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($params['column'] => $params['value'])), $this->_get->toInt('id'), 'pjDiscountPackage');
		}
		self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
	}
	
	public function pjActionDeletePackage()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}

		if (pjDiscountPackageModel::factory()->set('id', $this->_get->toInt('id'))->erase()->getAffectedRows() == 1)
		{
			pjDiscountPackageItemModel::factory()->where('package_id', $this->_get->toInt('id'))->eraseAll();
			$response = array('status' => 'OK', 'code' => 200, 'text' => '');
		} else {
			$response = array('status' => 'ERR', 'code' => 100, 'text' => '');
		}
		self::jsonResponse($response);
	}
	
	public function pjActionDeletePackageBulk()
	{
		$this->setAjax(true);
	
		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.'));
		}
		
		if (!$this->_post->has('record') || !($record = $this->_post->toArray('record')))
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Missing, empty or invalid data.'));
		}
		
		if (pjDiscountPackageModel::factory()->whereIn('id', $record)->eraseAll()->getAffectedRows() > 0)
		{
			pjDiscountPackageItemModel::factory()->whereIn('package_id', $record)->eraseAll();
			self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
		}

		self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
	}
	
	public function pjActionPackageItems()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
	}
	
	public function pjActionPackageAddItem()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		if (self::isPost() && $this->_post->check('add_item'))
		{
			$pjDiscountPackageItemModel = pjDiscountPackageItemModel::factory();
			$adults = $this->_post->toArray('adults');
			foreach ($adults as $k => $v)
			{
				if ($v > 0) {
					$package_id = $this->_post->toInt('package_id');
					$children = $this->_post->toArray('children');
					$price = $this->_post->toArray('price');
					$pjDiscountPackageItemModel->addBatchRow(array($package_id, $v, $children[$k], $price[$k]));
				}
			}
			$pjDiscountPackageItemModel->setBatchFields(array('package_id', 'adults', 'children', 'price'))->insertBatch();
			
			self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Items have been added.'));
		}			
	}
	
	public function pjActionDeletePackageItem()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}

		if (pjDiscountPackageItemModel::factory()->set('id', $this->_get->toInt('id'))->erase()->getAffectedRows() == 1)
		{
			$response = array('status' => 'OK', 'code' => 200, 'text' => '');
		} else {
			$response = array('status' => 'ERR', 'code' => 100, 'text' => '');
		}
		self::jsonResponse($response);
	}
	
	public function pjActionGetPackageItems()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		$pjDiscountPackageItemModel = pjDiscountPackageItemModel::factory()
										->where('t1.package_id', $this->_get->toInt('package_id'));
			
		$column = 'adults';
		$direction = 'ASC';
		if ($this->_get->toString('column') && in_array(strtoupper($this->_get->toString('direction')), array('ASC', 'DESC')))
		{
			$column = $this->_get->toString('column');
			$direction = strtoupper($this->_get->toString('direction'));
		}

		$total = $pjDiscountPackageItemModel->findCount()->getData();
		$rowCount = $this->_get->toInt('rowCount') ? $this->_get->toInt('rowCount') : 10;
		$pages = ceil($total / $rowCount);
		$page = $this->_get->toInt('page') ? $this->_get->toInt('page') : 1;
		$offset = ((int) $page - 1) * $rowCount;
		if ($page > $pages)
		{
			$page = $pages;
		}

		$data = $pjDiscountPackageItemModel
					->orderBy("$column $direction")
					->limit($rowCount, $offset)
					->findAll()
					->getData();
		foreach ($data as $k => $v) {
			$data[$k]['price_formated'] = pjCurrency::formatPrice($v['price']);
		}	
		
		self::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
	}
	
	public function pjActionSavePackageItem()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		if (!self::isPost())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'HTTP method not allowed.'));
		}
		
		$params = array(
				'id' => $this->_get->toInt('id'),
				'column' => $this->_post->toString('column'),
				'value' => $this->_post->toString('value'),
		);
		if (!(isset($params['id'], $params['column'], $params['value'])
				&& pjValidation::pjActionNumeric($params['id'])
				&& pjValidation::pjActionNotEmpty($params['column'])))
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Missing, empty or invalid parameters.'));
		}
		
		$pjDiscountPackageItemModel = pjDiscountPackageItemModel::factory();
		if (!in_array($params['column'], $pjDiscountPackageItemModel->getI18n()))
		{
			if (in_array($params['column'], array('adults')))
			{
				if ((int) $params['value'] <= 0)
				{
					self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Invalid number of adults'));
				}
			}
			$pjDiscountPackageItemModel->set('id', $this->_get->toInt('id'))->modify(array($params['column'] => $params['value']));
		} else {
			pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($params['column'] => $params['value'])), $this->_get->toInt('id'), 'pjDiscountPackageItem');
		}
		self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
	}
	/* EndPackages */
}
?>