<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminRooms extends pjAppController
{
	public function pjActionIndex()
	{
	    $this->checkLogin();
	    if (!pjAuth::factory('pjAdminRooms', 'pjActionIndex')->hasAccess())
	    {
	        $this->sendForbidden();
	        return;
	    }
	    
		$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
		$this->appendJs('pjAdminRooms.js');
	}
	
	public function pjActionGetRoom()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		$pjRoomModel = pjRoomModel::factory()
						->join('pjMultiLang', "t2.model='pjRoom' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer');
			
		if ($q = $this->_get->toString('q'))
		{
			$q = str_replace(array('_', '%'), array('\_', '\%'), $pjRoomModel->escapeStr($q));
			$pjRoomModel->where('t2.content LIKE', "%$q%");
		}
			
		$column = 'name';
		$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 = $pjRoomModel->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 = $pjRoomModel
			->select(sprintf("t1.id, t1.adults, t1.children, t1.cnt, t2.content AS name, t1.calendar_id,
				(SELECT `small_path` FROM `%s` WHERE `foreign_id` = t1.id AND `model` = 'pjRoom' ORDER BY `sort` ASC LIMIT 1) AS `image`
			", pjGalleryModel::factory()->getTable()))
			->orderBy("$column $direction")
			->limit($rowCount, $offset)
			->findAll()
			->getData();
		foreach ($data as $k => $v) {
			$data[$k]['name'] = pjSanitize::clean($v['name']);
		}	
		self::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
	}
	
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if (!pjAuth::factory()->hasAccess())
		{
			$this->sendForbidden();
			return;
		}
		
		if (self::isPost() && $this->_post->check('action_create'))
		{
			$data = array();
			$data['calendar_id'] = $this->getForeignId();
			$room_id = pjRoomModel::factory(array_merge($this->_post->raw(), $data))->insert()->getInsertId();
			if ($room_id !== false && (int) $room_id > 0)
			{
				$i18n_arr = $this->_post->toI18n('i18n');
				if (!empty($i18n_arr))
				{
					pjMultiLangModel::factory()->saveMultiLang($i18n_arr, $room_id, 'pjRoom');
				}
				$numbers = $this->_post->toArray('number');
				if ($this->_post->check('number') && !empty($numbers))
				{
					$pjRoomNumberModel = pjRoomNumberModel::factory();
					$pjRoomNumberModel->setBatchFields(array('room_id', 'number'));
					foreach ($numbers as $number)
					{
						$pjRoomNumberModel->addBatchRow(array($room_id, $number));
					}
					$pjRoomNumberModel->insertBatch();
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminRooms&action=pjActionUpdate&id=$room_id&&err=AR03");
			} else {
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminRooms&action=pjActionIndex&err=AR04");
			}
		} 
		
		if (self::isGet())
		{
    		$locale_arr = pjLocaleModel::factory()->select('t1.*, t2.file')
				->join('pjLocaleLanguage', 't2.iso=t1.language_iso', 'left')
				->where('t2.file IS NOT NULL')
				->orderBy('t1.sort ASC')->findAll()->getData();
					
			$lp_arr = array();
			foreach ($locale_arr as $item)
			{
				$lp_arr[$item['id']."_"] = $item['file'];
			}
			$this->set('lp_arr', $locale_arr);
			$this->set('locale_str', self::jsonEncode($lp_arr));
			
			$this->set('is_flag_ready', $this->requestAction(array('controller' => 'pjLocale', 'action' => 'pjActionIsFlagReady'), array('return')));
			
    		$this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
    		$this->appendJs('pjAdminRooms.js');
		}
	}
	
	public function pjActionDelete()
	{
		$this->setAjax(true);
		
		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 (!pjAuth::factory()->hasAccess())
		{
		    self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Access denied.'));
		}
		$response = array();
		if (pjRoomModel::factory()->set('id', $this->_get->toInt('id'))->erase()->getAffectedRows() == 1)
		{
			pjMultiLangModel::factory()->where('model', 'pjRoom')->where('foreign_id', $this->_get->toInt('id'))->eraseAll();
			$pjGalleryModel = new pjGalleryModel();
			$gallery_arr = $pjGalleryModel
				->where('foreign_id', $this->_get->toInt('id'))
				->where('model', 'pjRoom')
				->findAll()->getData();
			if (!empty($gallery_arr))
			{
				$pjGalleryModel->eraseAll();
				foreach ($gallery_arr as $item)
				{
					@clearstatcache();
					if (!empty($item['small_path']) && is_file($item['small_path']))
					{
						@unlink($item['small_path']);
					}
					@clearstatcache();
					if (!empty($item['medium_path']) && is_file($item['medium_path']))
					{
						@unlink($item['medium_path']);
					}
					@clearstatcache();
					if (!empty($item['large_path']) && is_file($item['large_path']))
					{
						@unlink($item['large_path']);
					}
					@clearstatcache();
					if (!empty($item['source_path']) && is_file($item['source_path']))
					{
						@unlink($item['source_path']);
					}
				}
			}
			$response['status'] = 'OK';
		} else {
			$response['status'] = 'ERR';
		}
		self::jsonResponse($response);
	}
	
	public function pjActionDeleteBulk()
	{
		$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' => 103, 'text' => 'Missing, empty or invalid data.'));
		}
		if (!pjAuth::factory()->hasAccess())
		{
		    self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Access denied.'));
		}
		pjRoomModel::factory()->whereIn('id', $record)->eraseAll();
		pjMultiLangModel::factory()->where('model', 'pjRoom')->whereIn('foreign_id', $record)->eraseAll();
		$pjGalleryModel = new pjGalleryModel();
		$gallery_arr = $pjGalleryModel
			->whereIn('foreign_id', $record)
			->where('model', 'pjRoom')
			->findAll()->getData();
		if (!empty($gallery_arr))
		{
			$pjGalleryModel->eraseAll();
			foreach ($gallery_arr as $item)
			{
				@clearstatcache();
				if (!empty($item['small_path']) && is_file($item['small_path']))
				{
					@unlink($item['small_path']);
				}
				@clearstatcache();
				if (!empty($item['medium_path']) && is_file($item['medium_path']))
				{
					@unlink($item['medium_path']);
				}
				@clearstatcache();
				if (!empty($item['large_path']) && is_file($item['large_path']))
				{
					@unlink($item['large_path']);
				}
				@clearstatcache();
				if (!empty($item['source_path']) && is_file($item['source_path']))
				{
					@unlink($item['source_path']);
				}
			}
		}
		
		self::jsonResponse(array('status' => 'OK'));
	}
	
	public function pjActionSave()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$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.'));
			}
			$pjRoomModel = pjRoomModel::factory();
			if (!in_array($params['column'], $pjRoomModel->getI18n()))
			{
			    $pjRoomModel->where('id', $params['id'])->limit(1)->modifyAll(array($params['column'] => $params['value']));
			} else {
			    pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($params['column'] => $params['value'])), $params['id'], 'pjRoom');
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if (!pjAuth::factory()->hasAccess())
		{
			$this->sendForbidden();
			return;
		}
		
		if (self::isPost() && $this->_post->check('action_update'))
		{
			pjRoomModel::factory()->where('id', $this->_post->toInt('id'))->limit(1)->modifyAll($this->_post->raw());
			$i18n_arr = $this->_post->toI18n('i18n');
			if (!empty($i18n_arr))
			{
				pjMultiLangModel::factory()->updateMultiLang($i18n_arr, $this->_post->toInt('id'), 'pjRoom');
			}
			$numbers = $this->_post->toArray('number');
			if ($this->_post->check('number') && !empty($numbers))
			{
				$pjRoomNumberModel = pjRoomNumberModel::factory();
				$existing_id_arr = $pjRoomNumberModel->where('t1.room_id', $this->_post->toInt('id'))->orderBy('t1.id ASC')->findAll()->getDataPair(null, 'id');
				$number_id_arr = array();
				foreach ($numbers as $key => $val)
				{
					$rn = array();
					$rn['room_id'] = $this->_post->toInt('id');
					$rn['number'] = $val;
					if (strpos($key, 'new') !== false)
					{
						$pjRoomNumberModel->reset()->setAttributes($rn)->insert();
					} else {
						$number_id_arr[] = $key;
						$pjRoomNumberModel->reset()->set('id', $key)->modify($rn);
					}
				}
				$remove_id_arr = array_diff($existing_id_arr, $number_id_arr);
				if (!empty($remove_id_arr))
				{
					$pjRoomNumberModel->reset()->whereIn('id', $remove_id_arr)->eraseAll();
				}
			}
			pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminRooms&action=pjActionIndex&err=AR01");
		} 
		
		if (self::isGet())
		{
			$arr = pjRoomModel::factory()->find($this->_get->toInt('id'))->getData();
			if (count($arr) === 0)
			{
				pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminRooms&action=pjActionIndex&err=AR08");
			}
			$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjRoom');
			$this->set('arr', $arr);
			$this->set('number_arr', pjRoomNumberModel::factory()->where('t1.room_id', $arr['id'])->findAll()->getData());
			
			$locale_arr = pjLocaleModel::factory()->select('t1.*, t2.file')
							->join('pjLocaleLanguage', 't2.iso=t1.language_iso', 'left')
							->where('t2.file IS NOT NULL')
							->orderBy('t1.sort ASC')->findAll()->getData();
				
			$lp_arr = array();
			foreach ($locale_arr as $item)
			{
				$lp_arr[$item['id']."_"] = $item['file'];
			}
			$this->set('lp_arr', $locale_arr);
			$this->set('locale_str', self::jsonEncode($lp_arr));

			$this->set('is_flag_ready', $this->requestAction(array('controller' => 'pjLocale', 'action' => 'pjActionIsFlagReady'), array('return')));
			
			# Gallery plugin
			$this->appendCss('pj-gallery.css', pjObject::getConstant('pjGallery', 'PLUGIN_CSS_PATH'));
			$this->appendJs('ajaxupload.js', PJ_THIRD_PARTY_PATH . 'ajaxupload/');
			$this->appendJs('jquery.gallery.js', pjObject::getConstant('pjGallery', 'PLUGIN_JS_PATH'));
			
			$this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminRooms.js');
		}
	}
}
?>