<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminSlides extends pjAdmin
{
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['slide_create']))
			{
				$id = pjSlideModel::factory($_POST)->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$this->__pjActionUpload($id);
					
					$err = 'AS03';
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjSlide');
					}
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminSlides&action=pjActionUpdate&id=$id&err=$err");
				} else {
					$err = 'AS04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminSlides&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('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('pjAdminSlides.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			}
		} else {
			$this->set('status', 2);
		}
	}

	public function pjActionDeleteSlide()
	{
		$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.'));
			}

			$pjSlideModel = pjSlideModel::factory();
			$arr = $pjSlideModel->find($_GET['id'])->getData();
			if (empty($arr))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Slide not found.'));
			}
			if ($pjSlideModel->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', 'pjSlide')->where('foreign_id', $_GET['id'])->eraseAll();
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Slide have been deleted.'));
			}
			pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Slide have not been deleted.'));
		}
		exit;
	}
	
	public function pjActionDeleteSlideBulk()
	{
		$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.'));
			}
			$pjSlideModel = pjSlideModel::factory();
			$arr = $pjSlideModel->whereIn('id', $_POST['record'])->findAll()->getData();
			if (empty($arr))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Slide(s) not found.'));
			}
			$pjSlideModel->eraseAll();
			pjMultiLangModel::factory()->where('model', 'pjSlide')->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' => 'Slide(s) have been deleted.'));
		}
		exit;
	}
	
	public function pjActionDeleteSlideImage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (isset($_POST['id']) && (int) $_POST['id'] > 0)
			{
				$pjSlideModel = pjSlideModel::factory();
				$arr = $pjSlideModel->find($_POST['id'])->getData();
				if (!empty($arr))
				{
					$pjSlideModel->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' => 'Slide image have been deleted.'));
				}
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Slide not found.'));
			}
			pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing, empty or invalid parameters.'));
		}
		exit;
	}
	
	public function pjActionStatusSlide()
	{
		$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')))
			{
				pjSlideModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array('status' => $_GET['status']));
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Slide(s) have been modified.'));
			}
			pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing, empty or invalid parameters.'));
		}
		exit;
	}
	
	public function pjActionGetSlide()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			$pjSlideModel = pjSlideModel::factory()->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjSlide' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'title'", 'left outer');
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = $pjSlideModel->escapeString($_GET['q']);
				$q = str_replace(array('%', '_'), array('\%', '\_'), trim($q));
				$pjSlideModel->where('t2.content LIKE', "%$q%");
			}
			
			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('T', 'F')))
			{
				$pjSlideModel->where('t1.status', $_GET['status']);
			}

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

		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['slide_update']))
			{
				pjSlideModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll($_POST);
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjSlide');
				}
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminSlides&action=pjActionIndex&err=AS01");
				
			}
			
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$arr = pjSlideModel::factory()->find($_GET['id'])->getData();
				if (empty($arr))
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminSlides&action=pjActionIndex&err=AS08");
				}
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjSlide');
				$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('jquery.validate.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('pjAdminSlides.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			} else {
				pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminSlides&action=pjActionIndex&err=AS08");
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	private function __crop($src, $dst, $x, $y, $w, $h, $targ_w = 291, $targ_h = 302, $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())
		{
			$pjSlideModel = pjSlideModel::factory();
			
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$this->set('arr', $pjSlideModel->find($_GET['id'])->getData());
				return;
			}
			
			if (isset($_POST['id']) && (int) $_POST['id'] > 0)
			{
				$arr = $pjSlideModel->find($_POST['id'])->getData();
				if (!empty($arr) && !empty($arr['image_original']))
				{
					$dst = PJ_UPLOAD_PATH . 'slides/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']))
					{
						$pjSlideModel->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', pjSlideModel::factory()->find($_GET['id'])->getData());
			}
		}
	}
	
	private function __pjActionUpload($id)
	{
		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 . 'slides/o_' . md5($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 . 'slides/t_' . md5($id) . "." . $ext;
				if ($this->__crop($dst, $dst_thumb, 0, 0, 291, 302))
				{
					$data['image_thumb'] = $dst_thumb;
				}
				
				pjSlideModel::factory()->set('id', $id)->modify($data);
				
				return array('status' => 'OK', 'code' => 200, 'text' => 'Image have been uploaded.');
			}
			return array('status' => 'ERR', 'code' => 100, 'text' => $image->getError());
		}
		return array('status' => 'ERR', 'code' => 101, 'text' => 'Image not uploaded.');
	}
	
	public function pjActionUpload()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			pjAppController::jsonResponse( $this->__pjActionUpload($_POST['id']) );
		}
		exit;
	}
}
?>