<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminPackages extends pjAdmin
{
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			if (isset($_POST['package_create']))
			{
				$data = array();
				$data['calendar_id'] = $this->getForeignId();
				$id = pjPackageModel::factory(array_merge($_POST, $data))->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					if (isset($_POST['item_id']) && !empty($_POST['item_id']))
					{
						$pjPackageItemModel = pjPackageItemModel::factory()->setBatchFields(array('package_id', 'item_id'));
						foreach ($_POST['item_id'] as $item_id)
						{
							$pjPackageItemModel->addBatchRow(array($id, $item_id));
						}
						$pjPackageItemModel->insertBatch();
						
						if (isset($_POST['gallery_ids']) && !empty($_POST['gallery_ids']))
						{
							$gallery_ids = explode(",", $_POST['gallery_ids']);
							$pjPackageGalleryModel = pjPackageGalleryModel::factory()->setBatchFields(array('package_id', 'gallery_id'));
							foreach ($gallery_ids as $gallery_id)
							{
								$pjPackageGalleryModel->addBatchRow(array($id, $gallery_id));
							}
							$pjPackageGalleryModel->insertBatch();
						}
					}
					$err = 'AP03';
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjPackage');
					}
				} else {
					$err = 'AP04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminPackages&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('item_arr', pjItemModel::factory()
					->select('t1.*, t2.content AS title')
					->join('pjMultiLang', "t2.model='pjItem' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('t1.is_active', 1)
					->orderBy('title ASC')->findAll()->getData());
				
				$this->appendJs('jquery.multiselect.min.js', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendCss('jquery.multiselect.css', PJ_THIRD_PARTY_PATH . 'multiselect/');
				
				$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('pjAdminPackages.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeletePackage()
	{
		$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', 'package')
					->findCount()
					->getData();
				
				if ($bookings > 0)
				{
					pjPackageModel::factory()->set('id', $_GET['id'])->modify(array('is_active' => 0));
					pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
				} else {
					if (pjPackageModel::factory()->set('id', $_GET['id'])->erase()->getAffectedRows() == 1)
					{
						pjPackageItemModel::factory()->where('package_id', $_GET['id'])->eraseAll();
						pjPriceModel::factory()->where('foreign_id', $_GET['id'])->where('type', 'package')->eraseAll();
						pjMultiLangModel::factory()->where('model', 'pjPackage')->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 pjActionDeletePackageBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (isset($_POST['record']) && !empty($_POST['record']))
			{
				$pjPackageModel = pjPackageModel::factory();
				$items = $pjPackageModel
					->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` = 'package'
						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))
				{
					$pjPackageModel->reset()->whereIn('id', $items)->modifyAll(array('is_active' => 0));
				} else {
					$items[] = '-1';
				}
				
				$pjPackageModel->reset()->whereIn('id', $_POST['record'])->whereNotIn('id', $items)->eraseAll();
				pjPackageItemModel::factory()->whereIn('package_id', $_POST['record'])->whereNotIn('package_id', $items)->eraseAll();
				pjPriceModel::factory()->whereIn('foreign_id', $_POST['record'])->where('type', 'package')->whereNotIn('foreign_id', $items)->eraseAll();
				pjMultiLangModel::factory()->where('model', 'pjPackage')->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;
	}

	public function pjActionGetPackage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			$pjPackageModel = pjPackageModel::factory()
				->join('pjMultiLang', "t2.model='pjPackage' 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 = $pjPackageModel->escapeString($_GET['q']);
				$q = str_replace(array('%', '_'), array('\%', '\_'), trim($q));
				$pjPackageModel->where("t2.content LIKE '%$q%'");
			}

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

			$total = $pjPackageModel->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 = $pjPackageModel->select(sprintf("t1.*, t2.content AS title,
					(SELECT MIN(`cnt`) FROM `%s` WHERE `id` IN (SELECT `item_id` FROM `%s` WHERE `package_id` = `t1`.`id`)) AS `cnt`,
					(SELECT COUNT(*)
						FROM `%3\$s`
						INNER JOIN `%4\$s` AS `tb` ON tb.id = `booking_id`
						WHERE `foreign_id` = t1.id
						AND `type` = 'package'
						LIMIT 1) AS `bookings`",
					pjItemModel::factory()->getTable(), pjPackageItemModel::factory()->getTable(),
					pjBookingItemModel::factory()->getTable(), pjBookingModel::factory()->getTable()))
				->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('pjAdminPackages.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSavePackage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			$pjPackageModel = pjPackageModel::factory();
			if (!in_array($_POST['column'], $pjPackageModel->getI18n()))
			{
				$pjPackageModel->set('id', $_GET['id'])->modify(array($_POST['column'] => $_POST['value']));
			} else {
				pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($_POST['column'] => $_POST['value'])), $_GET['id'], 'pjPackage');
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			if (isset($_POST['package_update']) && isset($_POST['id']) && (int) $_POST['id'] > 0)
			{
				$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';
				pjPackageModel::factory()->set('id', $_POST['id'])->modify(array_merge($_POST, $data));
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjPackage');
				}
				
				$pjPackageGalleryModel = pjPackageGalleryModel::factory();
				$pjPackageGalleryModel->where('package_id', $_POST['id'])->eraseAll();
				
				$pjPackageItemModel = pjPackageItemModel::factory();
				$pjPackageItemModel->where('package_id', $_POST['id'])->eraseAll();
				if (isset($_POST['item_id']) && !empty($_POST['item_id']))
				{
					$pjPackageItemModel->reset()->setBatchFields(array('package_id', 'item_id'));
					foreach ($_POST['item_id'] as $item_id)
					{
						$pjPackageItemModel->addBatchRow(array($_POST['id'], $item_id));
					}
					$pjPackageItemModel->insertBatch();
					
					if (isset($_POST['gallery_ids']) && !empty($_POST['gallery_ids']))
					{
						$gallery_ids = explode(",", $_POST['gallery_ids']);
						$pjPackageGalleryModel->reset()->setBatchFields(array('package_id', 'gallery_id'));
						foreach ($gallery_ids as $gallery_id)
						{
							$pjPackageGalleryModel->addBatchRow(array($_POST['id'], $gallery_id));
						}
						$pjPackageGalleryModel->insertBatch();
					}
				}
				
				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'] = 'package';
						$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);
						}
					}
				}
				pjUtil::redirect(sprintf("%sindex.php?controller=pjAdminPackages&action=pjActionUpdate&id=%u&err=AP01", PJ_INSTALL_URL, $_POST['id']));
				
			} else {
				$arr = pjPackageModel::factory()->find($_GET['id'])->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminPackages&action=pjActionIndex&err=AP08");
				}
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjPackage');
				$this->set('arr', $arr);
				
				$this->set('price_arr', pjPriceModel::factory()
					->where('t1.foreign_id', $arr['id'])
					->where('t1.type', 'package')
					->orderBy('t1.date_from DESC, t1.date_to DESC, t1.length_from ASC, t1.length_to ASC')
					->findAll()
					->getData()
				);
				
				$this->set('item_arr', pjItemModel::factory()
					->select('t1.*, t2.content AS title')
					->join('pjMultiLang', "t2.model='pjItem' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->orderBy('title ASC')->findAll()->getData());
				
				$pi_arr = pjPackageItemModel::factory()->where('package_id', $arr['id'])->findAll()->getDataPair(null, 'item_id');	
				$this->set('pi_arr', $pi_arr);
				
				$pg_arr = pjPackageGalleryModel::factory()->where('package_id', $arr['id'])->findAll()->getDataPair(null, 'gallery_id');
				$this->set('pg_arr', $pg_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']; //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));
				
				$gallery_arr  = array();
				if (!empty($pi_arr))
				{
					$tmp_arr = pjGalleryModel::factory()
						->whereIn('t1.foreign_id', $pi_arr)
						->findAll()
						->getData();
				
						
					foreach ($tmp_arr as $tmp)
					{
						if (!array_key_exists($tmp['foreign_id'], $gallery_arr))
						{
							$gallery_arr[$tmp['foreign_id']] = array();
						}
						$gallery_arr[$tmp['foreign_id']][] = $tmp;
					}
				}
				$this->set('gallery_arr', $gallery_arr);
				
				$this->appendJs('jquery.multiselect.min.js', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendCss('jquery.multiselect.css', PJ_THIRD_PARTY_PATH . 'multiselect/');
				
				$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('pjAdminPackages.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetItemGallery()
	{
		$this->setAjax(true);
		
		if ($this->isXHR() && $this->isLoged())
		{
			if(!empty($_GET['item_ids']) && $_GET['item_ids'] != 'null')
			{
				$gallery_arr  = array();
				$tmp_arr = pjGalleryModel::factory()
					->where('t1.foreign_id IN('.$_GET['item_ids'].')')
					->findAll()
					->getData();
				foreach ($tmp_arr as $tmp)
				{
					if (!array_key_exists($tmp['foreign_id'], $gallery_arr))
					{
						$gallery_arr[$tmp['foreign_id']] = array();
					}
					$gallery_arr[$tmp['foreign_id']][] = $tmp;
				}
				$this->set('gallery_arr', $gallery_arr);
			}
		}
	}
}
?>