<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminSpaces extends pjAdmin
{
    public function pjActionCheckPeriods()
    {
        $this->setAjax(true);
        if ($this->isXHR())
        {
            $post = $this->_post->raw();
            if (isset($post['date_from']) && count($post['date_from']) > 1)
            {
                foreach ($post['date_from'] as $index => $date_from)
                {
                    $date_to = $post['date_to'][$index];
                    $date_from = pjDateTime::formatDate($date_from, $this->option_arr['o_date_format']);
                    $date_to = pjDateTime::formatDate($date_to, $this->option_arr['o_date_format']);
                    foreach ($post['date_from'] as $idx => $check_date_from)
                    {
                        if($index != $idx)
                        {
                            $check_date_to = $post['date_to'][$idx];
                            $check_date_from = pjDateTime::formatDate($check_date_from, $this->option_arr['o_date_format']);
                            $check_date_to = pjDateTime::formatDate($check_date_to, $this->option_arr['o_date_format']);
                            
                            if(($check_date_from <= $date_from && $date_from <= $check_date_to) || ($check_date_to >= $date_to && $date_to >= $check_date_from))
                            {
                                self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'index' => $index, 'idx' => $idx, 'text' => __('lblDuplicatedPeriod', true)));
                            }
                        }
                    }
                }
            }
        }
        self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
    }
    
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if (!pjAuth::factory()->hasAccess())
		{
			$this->sendForbidden();
			return;
		}
		
		if (self::isPost() && $this->_post->check('action_create'))
		{
			$post = $this->_post->raw();
			$id = pjSpaceModel::factory($post)->insert()->getInsertId();
			if ($id !== false && (int) $id > 0)
			{
				$i18n_arr = $this->_post->toI18n('i18n');
				if (!empty($i18n_arr))
				{
					pjMultiLangModel::factory()->saveMultiLang($i18n_arr, $id, 'pjSpace');
				}
				$err = 'AS03';
				
				if (isset($post['date_from']) && count($post['date_from']) > 0)
				{
					$pjSpaceDateModel = pjSpaceDateModel::factory();
					$pjSpaceDateModel->begin();
					foreach ($post['date_from'] as $k => $v)
					{
						if (!empty($v) && !empty($post['date_to'][$k]))
						{
							$pjSpaceDateModel
								->reset()
								->set('space_id', $id)
								->set('date_from', pjDateTime::formatDate($post['date_from'][$k], $this->option_arr['o_date_format']))
								->set('date_to', pjDateTime::formatDate($post['date_to'][$k], $this->option_arr['o_date_format']))
								->set('spaces', $post['spaces'][$k])
								->insert();
						}
					}
					$pjSpaceDateModel->commit();
				}
			} else {
				$err = 'AS04';
			}
			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminSpaces&action=pjActionIndex&err=$err");
		} 
		
		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' => 'pjBaseLocale', 'action' => 'pjActionIsFlagReady'), array('return')));
			
    		$this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
    		$this->appendJs('tinymce.min.js', PJ_THIRD_PARTY_PATH . 'tinymce/');
    		$this->appendCss('datepicker3.css', PJ_THIRD_PARTY_PATH . 'bootstrap_datepicker/');
			$this->appendJs('bootstrap-datepicker.js', PJ_THIRD_PARTY_PATH . 'bootstrap_datepicker/');
    		$this->appendJs('pjAdminSpaces.js');
		}
	}

	public function pjActionDelete()
	{
		$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 (!pjAuth::factory()->hasAccess())
		{
		    self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Access denied.'));
		}
		$id = $this->_get->toInt('id');
		$response = array();
		if (pjSpaceModel::factory()->setAttributes(array('id' => $id))->erase()->getAffectedRows() == 1)
		{
			pjMultiLangModel::factory()->where('model', 'pjSpace')->where('foreign_id', $id)->eraseAll();
			pjDiscountModel::factory()->where('space_id', $id)->eraseAll();
			pjPriceModel::factory()->where('space_id', $id)->eraseAll();
			pjSpaceDateModel::factory()->where('space_id', $id)->eraseAll();
			
			$response['status'] = 'OK';
		} else {
			$response['status'] = 'ERR';
		}
		self::jsonResponse($response);
	}
	
	public function pjActionDeleteBulk()
	{
		$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.'));
		}
		
		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.'));
		}
		
		pjSpaceModel::factory()->whereIn('id', $record)->eraseAll();
		pjMultiLangModel::factory()->where('model', 'pjSpace')->whereIn('foreign_id', $record)->eraseAll();
		pjDiscountModel::factory()->whereIn('space_id', $record)->eraseAll();
		pjPriceModel::factory()->whereIn('space_id', $record)->eraseAll();
		pjSpaceDateModel::factory()->whereIn('space_id', $record)->eraseAll();
		
		self::jsonResponse(array('status' => 'OK'));
	}
	
	public function pjActionGetSpace()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		$pjSpaceModel = pjSpaceModel::factory()
			->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjSpace' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
			->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjSpace' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'description'", 'left');
		
		if ($q = $this->_get->toString('q'))
		{
			$q = str_replace(array('_', '%'), array('\_', '\%'), $pjSpaceModel->escapeStr($q));
			$pjSpaceModel->where('(t2.content LIKE "%'.$q.'%" OR t3.content LIKE "%'.$q.'%")');
		}
		if ($this->_get->toString('status') && in_array($this->_get->toString('status'), array('T', 'F')))
		{
			$pjSpaceModel->where('t1.status', $this->_get->toString('status'));
		}

		$column = 'name';
		$direction = 'ASC';
		$allowed_columns = array('name', 'booked', 'avail', 'price', 'status');
		if ($this->_get->toString('column') && in_array($this->_get->toString('column'), $allowed_columns) && in_array(strtoupper($this->_get->toString('direction')), array('ASC', 'DESC')))
		{
			$column = $this->_get->toString('column');
			$direction = strtoupper($this->_get->toString('direction'));
		}

		$total = $pjSpaceModel->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;
		}
		$now = date('Y-m-d H:i:s');
		$data = $pjSpaceModel
		->select(sprintf("t1.id, t1.status, t2.content AS name,
					  (SELECT `price` FROM `%1\$s` WHERE space_id = t1.id AND (CURDATE() BETWEEN `date_from` AND `date_to`) LIMIT 1) AS `price`,
					  (SELECT `spaces` FROM `%2\$s` WHERE space_id = t1.id AND (CURDATE() BETWEEN `date_from` AND `date_to`) LIMIT 1) AS `total`,
					  (SELECT COUNT(*) FROM `%3\$s` WHERE space_id = t1.id AND `status` = 'confirmed' AND ('".$now."' BETWEEN `from` AND `to`) LIMIT 1) AS `booked`", 
		    pjPriceModel::factory()->getTable(), pjSpaceDateModel::factory()->getTable(), pjBookingModel::factory()->getTable()))
			->orderBy("$column $direction")
			->limit($rowCount, $offset)
			->findAll()
			->getData();
		
		foreach($data as $k => $v)
		{
		    $avail = (int) $v['total'] - (int) $v['booked'];
			$v['name'] = pjSanitize::html($v['name']);
			$v['price'] = (float) $v['price'] > 0 ? pjCurrency::formatPrice($v['price']) : '';
			$v['avail'] = $avail >= 0 ? $avail : 0;
			$data[$k] = $v;
		}
		self::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
	    if (!pjAuth::factory('pjAdminSpaces', 'pjActionIndex')->hasAccess())
	    {
	        $this->sendForbidden();
	        return;
	    }
	    
		$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
		$this->appendJs('pjAdminSpaces.js');
	}
	
	public function pjActionSaveSpace()
	{
		$this->checkLogin();
		$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.'));
			}
			$pjSpaceModel = pjSpaceModel::factory();
			if (!in_array($params['column'], $pjSpaceModel->getI18n()))
			{
			    $pjSpaceModel->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'], 'pjSpace');
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if (!pjAuth::factory()->hasAccess())
		{
			$this->sendForbidden();
			return;
		}
		
		if (self::isPost() && $this->_post->check('action_update'))
		{
			$post = $this->_post->raw();
			pjSpaceModel::factory()->where('id', $this->_post->toInt('id'))->limit(1)->modifyAll($post);
			$i18n_arr = $this->_post->toI18n('i18n');
			if (!empty($i18n_arr))
			{
				pjMultiLangModel::factory()->updateMultiLang($i18n_arr, $this->_post->toInt('id'), 'pjSpace');
			}
			
			$pjSpaceDateModel = pjSpaceDateModel::factory();
			$pjSpaceDateModel->where('space_id', $post['id'])->eraseAll();
			if (isset($post['date_from']) && count($post['date_from']) > 0)
			{
				$pjSpaceDateModel->begin();
				foreach ($post['date_from'] as $k => $v)
				{
					if (!empty($v) && !empty($post['date_to'][$k]))
					{
						$pjSpaceDateModel
							->reset()
							->set('space_id', $post['id'])
							->set('date_from', pjDateTime::formatDate($post['date_from'][$k], $this->option_arr['o_date_format']))
							->set('date_to', pjDateTime::formatDate($post['date_to'][$k], $this->option_arr['o_date_format']))
							->set('spaces', $post['spaces'][$k])
							->insert();
					}
				}
				$pjSpaceDateModel->commit();
			}
			
			pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminSpaces&action=pjActionIndex&err=AS01");
		} 
		
		if (self::isGet())
		{
			$arr = pjSpaceModel::factory()->find($this->_get->toInt('id'))->getData();
			if (count($arr) === 0)
			{
				pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminSpaces&action=pjActionIndex&err=AS08");
			}
			$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjSpace');
			$this->set('arr', $arr);
			
			$sd_arr = pjSpaceDateModel::factory()
				->where('t1.space_id', $arr['id'])
				->findAll()
				->getData();
			$this->set('sd_arr', $sd_arr);
			
			$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' => 'pjBaseLocale', 'action' => 'pjActionIsFlagReady'), array('return')));
			
			$this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
    		$this->appendJs('tinymce.min.js', PJ_THIRD_PARTY_PATH . 'tinymce/');
    		$this->appendCss('datepicker3.css', PJ_THIRD_PARTY_PATH . 'bootstrap_datepicker/');
			$this->appendJs('bootstrap-datepicker.js', PJ_THIRD_PARTY_PATH . 'bootstrap_datepicker/');
    		$this->appendJs('pjAdminSpaces.js');
		}
	}
}
?>