<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminBooths extends pjAdmin
{
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			if (isset($_POST['booth_create']))
			{
				$pjBoothModel = pjBoothModel::factory();
				
				$id = $pjBoothModel->setAttributes($_POST)->insert()->getInsertId();
				
				if ($id !== false && (int) $id > 0)
				{
					$err = 'ABT03';
					
					$pjMultiLangModel = pjMultiLangModel::factory();
					$pjMultiLangModel->saveMultiLang($_POST['i18n'], $id, 'pjBooth', 'data');
					
					if (isset($_FILES['image']))
					{
						if($_FILES['image']['error'] == 0)
						{
							if(getimagesize($_FILES['image']["tmp_name"]) != false)
							{
								$Image = new pjImage();
								if ($Image->getErrorCode() !== 200)
								{
									$Image->setAllowedTypes(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg'));
									if ($Image->load($_FILES['image']))
									{
										$resp = $Image->isConvertPossible();
										if ($resp['status'] === true)
										{
											$hash = md5(uniqid(rand(), true));
											$image_path = PJ_UPLOAD_PATH . 'booths/' . $id . '_' . $hash . '.' . $Image->getExtension();
											$thumb_path = PJ_UPLOAD_PATH . 'booths/thumbs/' . $id . '_' . $hash . '.' . $Image->getExtension();
											
											$data = array();
											
											$data['image'] = $image_path;
											$data['thumb'] = $thumb_path;
											
											$Image->loadImage($_FILES['image']["tmp_name"]);
											$Image->saveImage($image_path);
												
											$Image->loadImage($_FILES['image']["tmp_name"]);
											$Image->resizeSmart(257, 170);
											$Image->saveImage($thumb_path);
												
											$pjBoothModel->reset()->where('id', $id)->limit(1)->modifyAll($data);
										}
									}
								}
							}else{
								$err = 'ABT09';
							}
						}else if($_FILES['image']['error'] != 4){
							$err = 'ABT09';
						}
					}
					if($err != 'ABT03')
					{
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBooths&action=pjActionUpdate&id=$id&err=ABT09");
					}
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBooths&action=pjActionUpdate&id=$id&err=$err");
				} else {
					$err = 'ABT04';
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBooths&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']; 
				}
				$this->set('lp_arr', $locale_arr);
				$this->set('locale_str', pjAppController::jsonEncode($lp_arr));
		
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$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('pjAdminBooths.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
		
	public function pjActionDeleteBooth()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			$pjBoothModel = pjBoothModel::factory();
			$arr = $pjBoothModel->find($_GET['id'])->getData();
			
			if ($pjBoothModel->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				if (file_exists(PJ_INSTALL_PATH . $arr['image'])) 
				{
					@unlink(PJ_INSTALL_PATH . $arr['image']);
				}
				if (file_exists(PJ_INSTALL_PATH . $arr['thumb']))
				{
					@unlink(PJ_INSTALL_PATH . $arr['thumb']);
				}
				
				pjMultiLangModel::factory()->where('model', 'pjBooth')->where('foreign_id', $_GET['id'])->eraseAll();
				pjPriceModel::factory()->where('booth_id', $_GET['id'])->eraseAll();
								
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteBoothBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				$pjBoothModel = pjBoothModel::factory();
				$arr = $pjBoothModel->whereIn('id', $_POST['record'])->findAll()->getData();
				foreach($arr as $v)
				{
					if (file_exists(PJ_INSTALL_PATH . $v['image'])) {
						@unlink(PJ_INSTALL_PATH . $v['image']);
					}
					if (file_exists(PJ_INSTALL_PATH . $v['thumb'])) {
						@unlink(PJ_INSTALL_PATH . $v['thumb']);
					}
				}
				
				$pjBoothModel->reset()->whereIn('id', $_POST['record'])->eraseAll();
				pjMultiLangModel::factory()->where('model', 'pjBooth')->whereIn('foreign_id', $_POST['record'])->eraseAll();
				
				pjPriceModel::factory()->whereIn('booth_id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionGetBooth()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjBoothModel = pjBoothModel::factory()
				->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjBooth' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'type'", 'left');
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjBoothModel->where('t2.content LIKE', "%$q%");
			}
			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('T', 'F')))
			{
				$pjBoothModel->where('t1.status', $_GET['status']);
			}

			$column = 'type';
			$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 = $pjBoothModel->findCount()->getData();
			$rowCount = isset($_GET['rowCount']) && (int) $_GET['rowCount'] > 0 ? (int) $_GET['rowCount'] : 20;
			$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 = $pjBoothModel
				->select('t1.*, t2.content AS type')
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();
			foreach($data as $k => $v)
			{
				$v['price'] = pjUtil::formatCurrencySign($v['price'], $this->option_arr['o_currency']);
				$data[$k] = $v;
			}
				
			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('pjAdminBooths.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveBooth()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjBoothModel = pjBoothModel::factory();
			if (!in_array($_POST['column'], $pjBoothModel->getI18n()))
			{
				$pjBoothModel->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
			} else {
				pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($_POST['column'] => $_POST['value'])), $_GET['id'], 'pjBooth', 'data');
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();

		if ($this->isAdmin())
		{
			if (isset($_POST['booth_update']))
			{
				$pjBoothModel = pjBoothModel::factory();
				
				$err = 'ABT01';
				
				$arr = $pjBoothModel->find($_POST['id'])->getData();
				if (empty($arr))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBooths&action=pjActionIndex&err=ABT08");
				}
				
				$data = array();
				
				if (isset($_FILES['image']))
				{
					if($_FILES['image']['error'] == 0)
					{
						if(getimagesize($_FILES['image']["tmp_name"]) != false)
						{
							$Image = new pjImage();
							if ($Image->getErrorCode() !== 200)
							{
								$Image->setAllowedTypes(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg'));
								if ($Image->load($_FILES['image']))
								{
									$resp = $Image->isConvertPossible();
									if ($resp['status'] === true)
									{
										if(!empty($arr['image']))
										{
											@unlink(PJ_INSTALL_PATH . $arr['image']);
										}
										if(!empty($arr['thumb']))
										{
											@unlink(PJ_INSTALL_PATH . $arr['thumb']);
										}
										
										$hash = md5(uniqid(rand(), true));
										$image_path = PJ_UPLOAD_PATH . 'booths/' . $_POST['id'] . '_' . $hash . '.' . $Image->getExtension();
										$thumb_path = PJ_UPLOAD_PATH . 'booths/thumbs/' . $_POST['id'] . '_' . $hash . '.' . $Image->getExtension();
										
										$Image->loadImage($_FILES['image']["tmp_name"]);
										$Image->saveImage($image_path);
										
										$Image->loadImage($_FILES['image']["tmp_name"]);
										$Image->resizeSmart(257, 170);
										$Image->saveImage($thumb_path);
										
										$data['image'] = $image_path;
										$data['thumb'] = $thumb_path;
									}
								}
							}
						}else{
							$err = 'ABT10';
						}
					}else if($_FILES['image']['error'] != 4){
						$err = 'ABT10';
					}
				}
				
				$pjBoothModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll(array_merge($_POST, $data));
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjBooth', 'data');
				}
				
				if($err == 'ABT01')
				{
					pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminBooths&action=pjActionUpdate&id=".$_POST['id']."&tab_id=".$_POST['tab_id']."&err=ABT01");
				}else{
					pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminBooths&action=pjActionUpdate&id=".$_POST['id']."&err=ABT10");
				}
			} else {
				$arr = pjBoothModel::factory()->find($_GET['id'])->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminBooths&action=pjActionIndex&err=ABT08");
				}
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjBooth');
				$this->set('arr', $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', pjAppController::jsonEncode($lp_arr));
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$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('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
				$this->appendJs('pjAdminBooths.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetPrice()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjPriceModel = pjPriceModel::factory();
				
			if (isset($_GET['booth_id']) && (int) $_GET['booth_id'] > 0)
			{
				$pjPriceModel->where('t1.booth_id', $_GET['booth_id']);
			}
	
			$column = 'date';
			$direction = 'DESC';
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}
	
			$total = $pjPriceModel->findCount()->getData();
			$rowCount = isset($_GET['rowCount']) && (int) $_GET['rowCount'] > 0 ? (int) $_GET['rowCount'] : 20;
			$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 = $pjPriceModel
				->select('t1.*')
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();
			foreach($data as $k => $v)
			{
				$v['date'] = date($this->option_arr['o_date_format'], strtotime($v['date']));
				$v['price'] = pjUtil::formatCurrencySign($v['price'], $this->option_arr['o_currency']);
				$data[$k] = $v;
			}
	
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionCustomPrice()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
	
			
			if(isset($_POST['id']))
			{
				$pjPriceModel = pjPriceModel::factory();
				
				$data = array();
				$data['date'] = pjUtil::formatDate($_POST['date'], $this->option_arr['o_date_format']);
				
				if((int) $_POST['id'] > 0)
				{
					$pjPriceModel->where('id', $_POST['id'])->limit(1)->modifyAll(array_merge($_POST, $data));
					$response['code'] = 200;
				}else{
					$id = $pjPriceModel->setAttributes(array_merge($_POST, $data))->insert()->getInsertId();
						
					if ($id !== false && (int) $id > 0)
					{
						$response['code'] = 200;
					}else{
						$response['code'] = 100;
					}
				}
			}else{
				$response['code'] = 100;
			}
			
			pjAppController::jsonResponse($response);
		}
	}
	
	public function pjActionDeletePrice()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
				
			if (pjPriceModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeletePriceBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjPriceModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionUpdatePrice()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$arr = pjPriceModel::factory()->find($_GET['id'])->getData();
			$arr['date'] = date($this->option_arr['o_date_format'], strtotime($arr['date']));
			$arr['code'] = 200;
			
			pjAppController::jsonResponse($arr);
		}
		exit;
	}
	
	public function pjActionDeleteImage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
				
			$pjBoothModel = pjBoothModel::factory();
			$arr = $pjBoothModel->find($_GET['id'])->getData();
				
			if(!empty($arr))
			{
				if(!empty($arr['image']))
				{
					@unlink(PJ_INSTALL_PATH . $arr['image']);
				}
				if(!empty($arr['thumb']))
				{
					@unlink(PJ_INSTALL_PATH . $arr['thumb']);
				}
	
				$data = array();
				$data['image'] = ':NULL';
				$data['thumb'] = ':NULL';
				$pjBoothModel->reset()->where(array('id' => $_GET['id']))->limit(1)->modifyAll($data);
	
				$response['code'] = 200;
			}else{
				$response['code'] = 100;
			}
				
			pjAppController::jsonResponse($response);
		}
	}
}
?>