<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminPages extends pjAdmin
{
	public function pjActionCheckUrl()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (!isset($_GET['seo_url']) || empty($_GET['seo_url']) || !preg_match('/^[\w\-]+$/', $_GET['seo_url']))
			{
				die("false");
			}
			
			$pjPageModel = pjPageModel::factory();
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$pjPageModel->where('t1.id !=', $_GET['id']);
			}
			echo 0 == $pjPageModel->where('t1.seo_url', $_GET['seo_url'])->findCount()->getData() ? "true" : "false";
			exit;
		}
		die("false");
	}
	
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['page_create']))
			{
				$id = pjPageModel::factory($_POST)->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$err = 'AP03';
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjPage');
					}
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminPages&action=pjActionUpdate&id=$id&err=$err");
				} else {
					$err = 'AP04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminPages&action=pjActionIndex&err=$err");
			} else {

				$locale_arr = pjLocaleModel::factory()->select('t1.*, t2.file')
					->join('pjLocaleLanguage', 't2.iso=t1.language_iso', 'left outer')
					->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->appendJs('tinymce.min.js', PJ_THIRD_PARTY_PATH . 'tinymce/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('jquery.friendurl.min.js', PJ_THIRD_PARTY_PATH . 'friendurl/');
				$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('pjAdminPages.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			}
		} else {
			$this->set('status', 2);
		}
	}

	public function pjActionDeletePage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (!isset($_GET['id']) || (int) $_GET['id'] <= 0)
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing, empty or invalid parameters.'));
			}
			$pjPageModel = pjPageModel::factory();
			$arr = $pjPageModel->find($_GET['id'])->getData();
			if (empty($arr))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Page not found.'));
			}
			if ($pjPageModel->erase()->getAffectedRows() == 1)
			{
				@clearstatcache();
				if (!empty($arr['image_original']) && is_file(PJ_INSTALL_PATH . $arr['image_original']))
				{
					@unlink(PJ_INSTALL_PATH . $arr['image_original']);
				}
				@clearstatcache();
				if (!empty($arr['image_thumb']) && is_file(PJ_INSTALL_PATH . $arr['image_thumb']))
				{
					@unlink(PJ_INSTALL_PATH . $arr['image_thumb']);
				}
				pjMultiLangModel::factory()->where('model', 'pjPage')->where('foreign_id', $_GET['id'])->eraseAll();
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Page have been deleted.'));
			}
			pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Page have not been deleted.'));
		}
		exit;
	}
	
	public function pjActionDeletePageBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (!isset($_POST['record']) || empty($_POST['record']))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing, empty or invalid parameters.'));
			}
			$pjPageModel = pjPageModel::factory();
			$arr = $pjPageModel->whereIn('id', $_POST['record'])->findAll()->getData();
			if (empty($arr))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Page(s) not found.'));
			}
			$pjPageModel->eraseAll();
			pjMultiLangModel::factory()->where('model', 'pjPage')->whereIn('foreign_id', $_POST['record'])->eraseAll();
			foreach ($arr as $item)
			{
				@clearstatcache();
				if (!empty($item['image_original']) && is_file(PJ_INSTALL_PATH . $item['image_original']))
				{
					@unlink(PJ_INSTALL_PATH . $item['image_original']);
				}
				@clearstatcache();
				if (!empty($item['image_thumb']) && is_file(PJ_INSTALL_PATH . $item['image_thumb']))
				{
					@unlink(PJ_INSTALL_PATH . $item['image_thumb']);
				}
			}
			pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Selected pages have been deleted.'));
		}
		exit;
	}
	
	public function pjActionDeletePageImage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (isset($_POST['id']) && (int) $_POST['id'] > 0)
			{
				$pjPageModel = pjPageModel::factory();
				$arr = $pjPageModel->find($_POST['id'])->getData();
				if (!empty($arr))
				{
					$pjPageModel->modify(array('image_thumb' => ':NULL', 'image_original' => ':NULL'));
					
					@clearstatcache();
					if (!empty($arr['image_thumb']) && is_file(PJ_INSTALL_PATH . $arr['image_thumb']))
					{
						@unlink(PJ_INSTALL_PATH . $arr['image_thumb']);
					}
					@clearstatcache();
					if (!empty($arr['image_original']) && is_file(PJ_INSTALL_PATH . $arr['image_original']))
					{
						@unlink(PJ_INSTALL_PATH . $arr['image_original']);
					}
					pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Page image have been deleted.'));
				}
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Page not found.'));
			}
			pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing, empty or invalid parameters.'));
		}
		exit;
	}
	
	public function pjActionStatusPage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (isset($_POST['record']) && !empty($_POST['record']) && isset($_GET['status']) && in_array($_GET['status'], array('T', 'F')))
			{
				pjPageModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array('status' => $_GET['status']));
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Selected pages have been modified.'));
			}
			pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing, empty or invalid parameters.'));
		}
		exit;
	}
	
	public function pjActionGetPage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			$pjPageModel = pjPageModel::factory()
				->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjPage' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left outer');
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = $pjPageModel->escapeString($_GET['q']);
				$q = str_replace(array('%', '_'), array('\%', '\_'), trim($q));
				$pjPageModel
					->where('t2.content LIKE', "%$q%");
			}
			
			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('T', 'F')))
			{
				$pjPageModel->where('t1.status', $_GET['status']);
			}

			$column = '`name`';
			$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 = $pjPageModel->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 = $pjPageModel->select('t1.*, t2.content AS `name`')
				->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->isEditor())
		{
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminPages.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSavePage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (!isset($_GET['id']) || (int) $_GET['id'] <= 0 || !isset($_POST['column']) || empty($_POST['column']) || !isset($_POST['value']))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing, empty or invalid parameters.'));
			}
			$pjPageModel = pjPageModel::factory();
			if (!in_array($_POST['column'], $pjPageModel->getI18n()))
			{
				$pjPageModel->set('id', $_GET['id'])->modify(array($_POST['column'] => $_POST['value']));
			} else {
				pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($_POST['column'] => $_POST['value'])), $_GET['id'], 'pjPage');
			}
			pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Page have been modified.'));
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();

		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['page_update']))
			{
				pjPageModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll($_POST);
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjPage');
				}
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminPages&action=pjActionIndex&err=AP01");
				
			}
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$arr = pjPageModel::factory()->find($_GET['id'])->getData();
				if (empty($arr))
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminPages&action=pjActionIndex&err=AP08");
				}
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjPage');
				$this->set('arr', $arr);
				
				$locale_arr = pjLocaleModel::factory()->select('t1.*, t2.file')
					->join('pjLocaleLanguage', 't2.iso=t1.language_iso', 'left outer')
					->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->appendCss('zino.core.css', PJ_THIRD_PARTY_PATH . 'zinoui/');
				$this->appendCss('zino.upload.css', PJ_THIRD_PARTY_PATH . 'zinoui/');
				$this->appendJs('zino.upload.min.js', PJ_THIRD_PARTY_PATH . 'zinoui/');
				$this->appendCss('jquery.Jcrop.min.css', PJ_THIRD_PARTY_PATH . 'jcrop/css/');
				$this->appendJs('jquery.Jcrop.min.js', PJ_THIRD_PARTY_PATH . 'jcrop/js/');
				$this->appendJs('tinymce.min.js', PJ_THIRD_PARTY_PATH . 'tinymce/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('jquery.friendurl.min.js', PJ_THIRD_PARTY_PATH . 'friendurl/');
				$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('pjAdminPages.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			} else {
				pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminPages&action=pjActionIndex&err=AP08");
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	private function __crop($src, $dst, $x, $y, $w, $h, $targ_w = 705, $targ_h = 355, $jpeg_quality = 100)
	{
		$img_r = imagecreatefromjpeg($src);
		$dst_r = imagecreatetruecolor($targ_w, $targ_h);
		
		imagecopyresampled($dst_r, $img_r, 0, 0, $x, $y, $targ_w, $targ_h, $w, $h);
		
		return imagejpeg($dst_r, $dst, $jpeg_quality);
	}
	
	public function pjActionCrop()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			$pjPageModel = pjPageModel::factory();
			
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$this->set('arr', $pjPageModel->find($_GET['id'])->getData());
				return;
			}
			
			if (isset($_POST['id']) && (int) $_POST['id'] > 0)
			{
				$arr = $pjPageModel->find($_POST['id'])->getData();
				if (!empty($arr) && !empty($arr['image_original']))
				{
					$dst = PJ_UPLOAD_PATH . 'pages/t_' . md5($arr['id']) . '.jpg';
					if ($this->__crop($arr['image_original'], $dst, $_POST['x'], $_POST['y'], $_POST['w'], $_POST['h']))
					{
						$pjPageModel->modify(array('image_thumb' => $dst));
						pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Image have been cropped.'));
					}
				}
			}
		}
	}
	
	public function pjActionImage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$this->set('arr', pjPageModel::factory()->find($_GET['id'])->getData());
			}
		}
	}
	
	public function pjActionUpload()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (isset($_FILES['image']) && !empty($_FILES['image']))
			{
				$pjImage = new pjImage();
				$pjImage
					->setAllowedExt(array('gif', 'png', 'jpg', 'jpeg'))
					->setAllowedTypes(array('image/gif', 'image/png', 'image/jpeg', 'image/jpg', 'image/pjpeg'));
				if ($pjImage->load($_FILES['image']))
				{
					$dst = PJ_UPLOAD_PATH . 'pages/o_' . md5($_POST['id']) . '.jpg';
					
					$pjImage->loadImage();
					if ($pjImage->getWidth() > 800)
					{
						$pjImage->resizeToWidth(800);
					}
					if ($pjImage->getHeight() > 800)
					{
						$pjImage->resizeToHeight(800);
					}
					$pjImage->saveImage($dst);
					$data = array('image_original' => $dst);
					
					$dst_thumb = PJ_UPLOAD_PATH . 'pages/t_' . md5($_POST['id']) . '.jpg';
					if ($this->__crop($dst, $dst_thumb, 0, 0, 705, 355))
					{
						$data['image_thumb'] = $dst_thumb;
					}
					
					pjPageModel::factory()->set('id', $_POST['id'])->modify($data);
					
					pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Image have been uploaded.'));
				}
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => $pjImage->getError()));
			}
			pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Image not uploaded.'));
		}
		exit;
	}
}
?>