<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminDestinations 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");
			}
			
			$pjDestinationModel = pjDestinationModel::factory();
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$pjDestinationModel->where('t1.id !=', $_GET['id']);
			}
			echo 0 == $pjDestinationModel->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['destination_create']))
			{
				$id = pjDestinationModel::factory($_POST)->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$err = 'AD03';
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjDestination');
					}
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminDestinations&action=pjActionUpdate&id=$id&err=$err");
				} else {
					$err = 'AD04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminDestinations&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->set('country_arr', pjCountryModel::factory()
					->select('t1.*, t2.content AS `country_title`')
					->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->orderBy('t2.content ASC')
					->findAll()
					->getData()
				);
				
				$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
			
				$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('pjAdminDestinations.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			}
		} else {
			$this->set('status', 2);
		}
	}

	public function pjActionDeleteDestination()
	{
		$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.'));
			}
			$pjDestinationModel = pjDestinationModel::factory();
			$arr = $pjDestinationModel->find($_GET['id'])->getData();
			if (empty($arr))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Destination not found.'));
			}
			if ($pjDestinationModel->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', 'pjDestination')->where('foreign_id', $_GET['id'])->eraseAll();
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Destination have been deleted.'));
			}
			
			pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Destination have not been deleted.'));
		}
		exit;
	}
	
	public function pjActionDeleteDestinationBulk()
	{
		$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.'));
			}
			$pjDestinationModel = pjDestinationModel::factory();
			$arr = $pjDestinationModel->whereIn('id', $_POST['record'])->findAll()->getData();
			if (empty($arr))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Destination(s) not found.'));
			}
			$pjDestinationModel->eraseAll();
			pjMultiLangModel::factory()->where('model', 'pjDestination')->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 destinations have been deleted.'));
		}
		exit;
	}
	
	public function pjActionDeleteDestinationImage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (isset($_POST['id']) && (int) $_POST['id'] > 0)
			{
				$pjDestinationModel = pjDestinationModel::factory();
				$arr = $pjDestinationModel->find($_POST['id'])->getData();
				if (!empty($arr))
				{
					$pjDestinationModel->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' => 'Destination image have been deleted.'));
				}
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Destination not found.'));
			}
			pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing, empty or invalid parameters.'));
		}
		exit;
	}
	
	public function pjActionStatusDestination()
	{
		$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')))
			{
				pjDestinationModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array('status' => $_GET['status']));
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Selected destinations have been modified.'));
			}
			pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing, empty or invalid parameters.'));
		}
		exit;
	}
	
	public function pjActionGetDestination()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			$pjDestinationModel = pjDestinationModel::factory()
				->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjDestination' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left outer')
				->join('pjMultiLang', "t3.foreign_id = t1.country_id AND t3.model = 'pjCountry' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'name'", 'left outer');
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = $pjDestinationModel->escapeString($_GET['q']);
				$q = str_replace(array('%', '_'), array('\%', '\_'), trim($q));
				$pjDestinationModel
					->where('t2.content LIKE', "%$q%")
					->orWhere('t3.content LIKE', "%$q%");
			}
			
			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('T', 'F')))
			{
				$pjDestinationModel->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 = $pjDestinationModel->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 = $pjDestinationModel->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('pjAdminDestinations.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveDestination()
	{
		$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.'));
			}
			$pjDestinationModel = pjDestinationModel::factory();
			if (!in_array($_POST['column'], $pjDestinationModel->getI18n()))
			{
				$pjDestinationModel->set('id', $_GET['id'])->modify(array($_POST['column'] => $_POST['value']));
			} else {
				pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($_POST['column'] => $_POST['value'])), $_GET['id'], 'pjDestination');
			}
			pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Destination have been modified.'));
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();

		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['destination_update']))
			{
				pjDestinationModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll($_POST);
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjDestination');
				}
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminDestinations&action=pjActionIndex&err=AD01");
				
			}
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$arr = pjDestinationModel::factory()->find($_GET['id'])->getData();
				if (empty($arr))
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminDestinations&action=pjActionIndex&err=AD08");
				}
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjDestination');
				$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->set('country_arr', pjCountryModel::factory()
					->select('t1.*, t2.content AS `country_title`')
					->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->orderBy('t2.content ASC')
					->findAll()
					->getData()
				);

				$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
			
				$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('pjAdminDestinations.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			} else {
				pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminDestinations&action=pjActionIndex&err=AD08");
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	private function __crop($src, $dst, $x, $y, $w, $h, $targ_w = 705, $targ_h = 355, $jpeg_quality = 100)
	{
		$info = getimagesize($src);
		switch ($info[2])
		{
			case IMAGETYPE_JPEG:
				$img_r = @imagecreatefromjpeg($src);
				break;
			case IMAGETYPE_GIF:
				$img_r = @imagecreatefromgif($src);
				break;
			case IMAGETYPE_PNG:
				$img_r = @imagecreatefrompng($src);
				break;
		}
		
		$dst_r = imagecreatetruecolor($targ_w, $targ_h);
		switch ($info[2])
		{
			case IMAGETYPE_GIF:
			case IMAGETYPE_PNG:
				imagealphablending($dst_r, false);
				imagesavealpha($dst_r, true);
				$transparent = imagecolorallocatealpha($dst_r, 255, 255, 255, 127);
				imagefilledrectangle($dst_r, 0, 0, $targ_w, $targ_h, $transparent);
				break;
		}
		
		imagecopyresampled($dst_r, $img_r, 0, 0, $x, $y, $targ_w, $targ_h, $w, $h);
		
		switch ($info[2])
		{
			case IMAGETYPE_JPEG:
				return imagejpeg($dst_r, $dst, $jpeg_quality);
				break;
			case IMAGETYPE_GIF:
				return imagegif($dst_r, $dst);
				break;
			case IMAGETYPE_PNG:
				return imagepng($dst_r, $dst);
				break;
		}
		
		return false;
	}
	
	public function pjActionCrop()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			$pjDestinationModel = pjDestinationModel::factory();
			
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$this->set('arr', $pjDestinationModel->find($_GET['id'])->getData());
				return;
			}
			
			if (isset($_POST['id']) && (int) $_POST['id'] > 0)
			{
				$arr = $pjDestinationModel->find($_POST['id'])->getData();
				if (!empty($arr) && !empty($arr['image_original']))
				{
					$dst = PJ_UPLOAD_PATH . 'destinations/t_' . md5($arr['id']) . '.' . pjUtil::getFileExtension(basename($arr['image_original']));
					if ($this->__crop($arr['image_original'], $dst, $_POST['x'], $_POST['y'], $_POST['w'], $_POST['h']))
					{
						$pjDestinationModel->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', pjDestinationModel::factory()->find($_GET['id'])->getData());
			}
		}
	}
	
	public function pjActionUpload()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (isset($_FILES['image']) && !empty($_FILES['image']))
			{
				$image = new pjImage();
				$image
					->setAllowedExt($this->imageExt)
					->setAllowedTypes($this->imageType)
				;
				if ($image->load($_FILES['image']))
				{
					$ext = $image->getExtension();
					$dst = PJ_UPLOAD_PATH . 'destinations/o_' . md5($_POST['id']) . "." . $ext;
					
					$image->loadImage();
					$width = $image->getWidth();
					$height = $image->getHeight();
					if ($width > 800)
					{
						$image->resizeToWidth(800);
					}
					if ($height > 800)
					{
						$image->resizeToHeight(800);
					}
					if ($width <= 800 && $height <= 800)
					{
						$image->resize($width, $height);
					}
					
					$info = $image->getImageSize();
					$image->saveImage($dst, $info[2]);
					
					$data = array('image_original' => $dst);
					
					$dst_thumb = PJ_UPLOAD_PATH . 'destinations/t_' . md5($_POST['id']) . "." . $ext;
					if ($this->__crop($dst, $dst_thumb, 0, 0, 705, 355))
					{
						$data['image_thumb'] = $dst_thumb;
					}
					
					pjDestinationModel::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' => $image->getError()));
			}
			pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Image not uploaded.'));
		}
		exit;
	}
}
?>