<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminItems extends pjAdmin
{
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			if (isset($_POST['item_create']))
			{
				$data = array();
				$data['calendar_id'] = $this->getForeignId();
				$id = pjItemModel::factory(array_merge($_POST, $data))->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$err = 'AI03';
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjItem');
					}
					
					pjGalleryModel::factory()
						->where('hash', $_POST['hash'])
						->modifyAll(array(
							'foreign_id' => $id,
							'hash' => ':NULL'
						));
					// TODO rename files
					
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminItems&action=pjActionUpdate&id=$id&err=$err");
				} else {
					$err = 'AI04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminItems&action=pjActionIndex&err=$err");
			} else {
				$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']; //Hack for jquery $.extend, to prevent (re)order of numeric keys in object
				}
				$this->set('lp_arr', $locale_arr);
				$this->set('locale_str', pjAppController::jsonEncode($lp_arr));
				
				$this->set('category_arr', pjCategoryModel::factory()
					->select('t1.*, t2.content AS title')
					->join('pjMultiLang', "t2.model='pjCategory' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'")
					->where('t1.calendar_id', $this->getForeignId())
					->where('t1.is_active', 1)
					->findAll()
					->getData()
				);
				
				# Gallery plugin
				
				$this->appendCss('pj-gallery.css', pjObject::getConstant('pjGallery', 'PLUGIN_CSS_PATH'));
				$this->appendJsFromPlugin('ajaxupload.js', 'ajaxupload', 'pjGallery');
				$this->appendJs('jquery.gallery.js', pjObject::getConstant('pjGallery', 'PLUGIN_JS_PATH'));
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				if ((int) $this->option_arr['o_multi_lang'] === 1)
				{
					$this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
					$this->appendJs('jquery.tipsy.js', PJ_THIRD_PARTY_PATH . 'tipsy/');
					$this->appendCss('jquery.tipsy.css', PJ_THIRD_PARTY_PATH . 'tipsy/');
				}
				$this->appendJs('pjAdminItems.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteItem()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$bookings = pjBookingItemModel::factory()
					->join('pjBooking', 't2.id=t1.booking_id', 'inner')
					->where('t1.foreign_id', $_GET['id'])
					->where('t1.type', 'item')
					->findCount()
					->getData();
				
				if ($bookings > 0)
				{
					pjItemModel::factory()->set('id', $_GET['id'])->modify(array('is_active' => 0));
					pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
				} else {
					if (pjItemModel::factory()->set('id', $_GET['id'])->erase()->getAffectedRows() == 1)
					{
						pjPriceModel::factory()->where('foreign_id', $_GET['id'])->where('type', 'item')->eraseAll();
						pjMultiLangModel::factory()->where('model', 'pjItem')->where('foreign_id', $_GET['id'])->eraseAll();
						pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
					}
				}
			}
			pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
		}
		exit;
	}
	
	public function pjActionDeleteItemBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (isset($_POST['record']) && !empty($_POST['record']))
			{
				$pjItemModel = pjItemModel::factory();
				$items = $pjItemModel
					->select(sprintf("t1.id, (
						SELECT COUNT(*)
						FROM `%1\$s`
						INNER JOIN `%2\$s` AS `tb` ON tb.id = `booking_id`
						WHERE `foreign_id` = t1.id
						AND `type` = 'item'
						LIMIT 1) AS `bookings`", pjBookingItemModel::factory()->getTable(), pjBookingModel::factory()->getTable()))
					->whereIn('t1.id', $_POST['record'])
					->having('bookings > 0')
					->findAll()
					->getDataPair(null, 'id');
				
				if (!empty($items))
				{
					$pjItemModel->reset()->whereIn('id', $items)->modifyAll(array('is_active' => 0));
				} else {
					$items[] = '-1';
				}
					
				$pjItemModel->reset()->whereIn('id', $_POST['record'])->whereNotIn('id', $items)->eraseAll();
				pjPriceModel::factory()->whereIn('foreign_id', $_POST['record'])->where('type', 'item')->whereNotIn('foreign_id', $items)->eraseAll();
				pjMultiLangModel::factory()->where('model', 'pjItem')->whereIn('foreign_id', $_POST['record'])->whereNotIn('foreign_id', $items)->eraseAll();
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
			}
			pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
		}
		exit;
	}
	
	public function pjActionDeletePrice()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (isset($_POST['id']) && (int) $_POST['id'] > 0 && pjPriceModel::factory()->set('id', $_POST['id'])->erase()->getAffectedRows() == 1)
			{
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Price has been deleted.'));
			}
			pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Price has not been deleted.'));
		}
		exit;
	}

	private function __getCalendar($item_id, $year, $month)
	{
		$pjACalendar = new pjACalendar();
		$pjACalendar
			->setPrevLink("")
			->setNextLink("")
			->set('options', $this->option_arr)
			->set('weekNumbers', false)
			->setStartDay($this->option_arr['o_week_start'])
			->setDayNames(__('day_names', true))
			->setMonthNames(__('months', true))
			->set('availability', pjAvailabilityModel::factory()
				->where('t1.item_id', $item_id)
				->where('YEAR(`dt`)', $year)
				->where('MONTH(`dt`)', $month)
				->findAll()
				->getDataPair(null, 'dt')
			);
		
		$this->set('ACalendar', $pjACalendar);
	}
	
	public function pjActionGetAvailability()
	{
		$this->setAjax(true);
		
		if ($this->isXHR() && $this->isLoged())
		{
			$this->__getCalendar($_GET['item_id'], $_GET['year'], $_GET['month']);
		} else {
			exit;
		}
	}
	
	public function pjActionGetItem()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			$pjItemModel = pjItemModel::factory()
				->join('pjMultiLang', "t2.model='pjItem' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->where('t1.calendar_id', $this->getForeignId());
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = $pjItemModel->escapeString($_GET['q']);
				$q = str_replace(array('%', '_'), array('\%', '\_'), trim($q));
				$pjItemModel->where("t2.content LIKE '%$q%'");
			}
			
			if (isset($_GET['category_id']) && (int) $_GET['category_id'] > 0)
			{
				$pjItemModel->where("t1.category_id", $_GET['category_id']);
			}

			if (isset($_GET['is_active']) && strlen($_GET['is_active']) > 0 && in_array((int) $_GET['is_active'], array(1, 0)))
			{
				$pjItemModel->where('t1.is_active', $_GET['is_active']);
			}
				
			$column = 'title';
			$direction = 'ASC';
			$allowed_columns = array('image', 'title', 'category_title', 'cnt', 'is_active');
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array($_GET['column'], $allowed_columns) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}

			$total = $pjItemModel->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 = $pjItemModel->select(sprintf("t1.*, t2.content AS title, t3.content AS category_title,
					(SELECT `small_path` FROM `%1\$s` WHERE `foreign_id` = `t1`.`id` ORDER BY `sort` ASC LIMIT 1) AS `image`,
					(SELECT COUNT(*)
						FROM `%2\$s`
						INNER JOIN `%3\$s` AS `tb` ON tb.id = `booking_id`
						WHERE `foreign_id` = t1.id
						AND `type` = 'item'
						LIMIT 1) AS `bookings`
				", pjGalleryModel::factory()->getTable(), pjBookingItemModel::factory()->getTable(), pjBookingModel::factory()->getTable()))
				->join('pjMultiLang', "t3.model='pjCategory' AND t3.foreign_id=t1.category_id AND t3.field='title' AND t3.locale='".$this->getLocaleId()."'", 'left outer')
				->orderBy("$column $direction")->limit($rowCount, $offset)->findAll()->getData();
				
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminItems.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveItem()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			$pjItemModel = pjItemModel::factory();
			if (!in_array($_POST['column'], $pjItemModel->getI18n()))
			{
				$pjItemModel->set('id', $_GET['id'])->modify(array($_POST['column'] => $_POST['value']));
			} else {
				pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($_POST['column'] => $_POST['value'])), $_GET['id'], 'pjItem');
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			if (isset($_POST['item_update']))
			{
				$by_hour = isset($_POST['rent_by_hour']);
				$by_day = isset($_POST['rent_by_day']);
				$by_both = $by_hour && $by_day;
				
				$data = array();
				$data['rent_by_hour'] = $by_hour ? 1 : 0;
				$data['rent_by_day'] = $by_day ? 1 : 0;
				$data['price_per_hour'] = $by_hour ? $_POST['price_per_hour'] : ':NULL';
				$data['price_per_day'] = $by_day ? $_POST['price_per_day'] : ':NULL';
				
				pjItemModel::factory()->set('id', $_POST['id'])->modify(array_merge($_POST, $data));
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjItem');
				}
				
				if (isset($_POST['date_from']) && !empty($_POST['date_from']))
				{
					$pjPriceModel = pjPriceModel::factory();
					
					foreach ($_POST['date_from'] as $k => $v)
					{
						if (empty($_POST['date_from'][$k]) || empty($_POST['date_to'][$k]) ||
							empty($_POST['length_from'][$k]) || empty($_POST['length_from'][$k]) || empty($_POST['price'][$k]))
						{
							continue;
						}
						
						$data = array();
						$data['type'] = 'item';
						$data['period'] = $by_both ? $_POST['period'][$k] : ($by_hour ? 'hour' : 'day');
						$data['date_from'] = pjUtil::formatDate($_POST['date_from'][$k], $this->option_arr['o_date_format']);
						$data['date_to'] = pjUtil::formatDate($_POST['date_to'][$k], $this->option_arr['o_date_format']);
						$data['length_from'] = $_POST['length_from'][$k];
						$data['length_to'] = $_POST['length_to'][$k];
						$data['price'] = $_POST['price'][$k];
						
						if (strpos($k, "x_") === 0)
						{
							// Insert new
							$data['foreign_id'] = $_POST['id'];
							
							$pjPriceModel
								->reset()
								->setAttributes($data)
								->insert();
						} else {
							// Update
							$pjPriceModel->reset()->set('id', $k)->modify($data);
						}
					}
				}
				
				$pjAvailabilityModel = pjAvailabilityModel::factory();					
				$pjAvailabilityModel->where('item_id', $_POST['id'])->eraseAll();
				if (isset($_POST['avail_date_from']) && !empty($_POST['avail_date_from']))
				{
					foreach ($_POST['avail_date_from'] as $k => $v)
					{
						if (empty($_POST['avail_date_from'][$k]) || empty($_POST['avail_date_to'][$k]))
						{
							continue;
						}
						$data = array();
						$data['item_id'] = $_POST['id'];
						$data['date_from'] = pjUtil::formatDate($_POST['avail_date_from'][$k], $this->option_arr['o_date_format']);
						$data['date_to'] = pjUtil::formatDate($_POST['avail_date_to'][$k], $this->option_arr['o_date_format']);
						$data['cnt'] = $_POST['avail_cnt'][$k];
						$pjAvailabilityModel->reset()->setAttributes($data)->insert();
					}
				}
				pjUtil::redirect(sprintf("%sindex.php?controller=pjAdminItems&action=pjActionUpdate&id=%u&err=AI01&tab=%u", PJ_INSTALL_URL, $_POST['id'], @$_POST['tab']));
				
			} else {
				$arr = pjItemModel::factory()->find($_GET['id'])->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminItems&action=pjActionIndex&err=AI08");
				}
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjItem');
				$this->set('arr', $arr);
				
				$this->set('price_arr', pjPriceModel::factory()
					->where('t1.foreign_id', $arr['id'])
					->where('t1.type', 'item')
					->orderBy('t1.date_from DESC, t1.date_to DESC, t1.length_from ASC, t1.length_to ASC')
					->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']; //Hack for jquery $.extend, to prevent (re)order of numeric keys in object
				}
				$this->set('lp_arr', $locale_arr);
				$this->set('locale_str', pjAppController::jsonEncode($lp_arr));
				
				$this->set('category_arr', pjCategoryModel::factory()
					->select('t1.*, t2.content AS title')
					->join('pjMultiLang', "t2.model='pjCategory' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'")
					->where('t1.calendar_id', $this->getForeignId())
					->findAll()
					->getData()
				);
				
				$this->set('avail_arr', pjAvailabilityModel::factory()
						->where('t1.item_id', $arr['id'])
						->where('(t1.date_from IS NOT NULL AND t1.date_to IS NOT NULL AND t1.cnt IS NOT NULL)')
						->orderBy('t1.date_from ASC')
						->findAll()
						->getData()
				);
				
				# Gallery plugin
				$this->appendCss('pj-gallery.css', pjObject::getConstant('pjGallery', 'PLUGIN_CSS_PATH'));
				$this->appendJsFromPlugin('ajaxupload.js', 'ajaxupload', 'pjGallery');
				$this->appendJs('jquery.gallery.js', pjObject::getConstant('pjGallery', 'PLUGIN_JS_PATH'));
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				if ((int) $this->option_arr['o_multi_lang'] === 1)
				{
					$this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
					$this->appendJs('jquery.tipsy.js', PJ_THIRD_PARTY_PATH . 'tipsy/');
					$this->appendCss('jquery.tipsy.css', PJ_THIRD_PARTY_PATH . 'tipsy/');
				}
				$this->appendJs('pjAdminItems.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			}
		} else {
			$this->set('status', 2);
		}
	}
}
?>