<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminBanners extends pjAdmin
{
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['banner_create']))
			{
				$data = array();
				$data['type'] = $_POST['type'];
				switch ($_POST['type'])
				{
					case 'image':
						$data['target'] = $_POST['target'];
						break;
					case 'code':
						break;
				}
				
				$id = pjBannerModel::factory($data)->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					if (isset($_FILES['image']))
					{
						$files = array();
						foreach ($_FILES['image']['tmp_name'] as $locale_id => $tmp_name)
						{
							$files[$locale_id] = array(
								'name' => $_FILES['image']['name'][$locale_id],
								'type' => $_FILES['image']['type'][$locale_id],
								'tmp_name' => $_FILES['image']['tmp_name'][$locale_id],
								'error' =>  $_FILES['image']['error'][$locale_id],
								'size' => $_FILES['image']['size'][$locale_id]
							);
						}
						
						$upload = new pjUpload();
						$upload->setAllowedExt($this->imageExt);
						$upload->setAllowedTypes($this->imageType);
						
						foreach ($files as $locale_id => $file)
						{
							if ($upload->load($file))
							{
								$dest = PJ_UPLOAD_PATH . 'banners/' . $id .'_'. md5(uniqid(rand(), true)) . '.' . $upload->getExtension();
								if ($upload->save($dest))
								{
									$_POST['i18n'][$locale_id]['image'] = $dest;
								}
							}
						}
					}
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjBanner');
					}
					$err = 'ABR03';
				} else {
					$err = 'ABR04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBanners&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('pjAdminBanners.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			}
		} else {
			$this->set('status', 2);
		}
	}

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

			$pjBannerModel = pjBannerModel::factory();
			if (0 == $pjBannerModel->where('t1.id', $_GET['id'])->findCount()->getData())
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Banner not found.'));
			}
			if ($pjBannerModel->reset()->set('id', $_GET['id'])->erase()->getAffectedRows() == 1)
			{
				$pjMultiLangModel = pjMultiLangModel::factory();
				$i18n = $pjMultiLangModel->getMultiLang($_GET['id'], 'pjBanner');
				foreach ($i18n as $data)
				{
					@clearstatcache();
					if (isset($data['image']) && !empty($data['image']) && is_file(PJ_INSTALL_PATH . $data['image']))
					{
						@unlink(PJ_INSTALL_PATH . $data['image']);
					}
				}
				
				$pjMultiLangModel->reset()->where('model', 'pjBanner')->where('foreign_id', $_GET['id'])->eraseAll();
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Banner have been deleted.'));
			}
			pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Banner have not been deleted.'));
		}
		exit;
	}
	
	public function pjActionDeleteBannerBulk()
	{
		$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.'));
			}
			$pjBannerModel = pjBannerModel::factory();
			if (0 == $pjBannerModel->whereIn('id', $_POST['record'])->findCount()->getData())
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Banner(s) not found.'));
			}
			$pjBannerModel->eraseAll();
			
			$pjMultiLangModel = pjMultiLangModel::factory();
			$i18n = $pjMultiLangModel
				->select('t1.content AS `image`')
				->where('t1.model', 'pjBanner')
				->whereIn('t1.foreign_id', $_POST['record'])
				->where('t1.field', 'image')
				->findAll()
				->getData();
			foreach ($i18n as $data)
			{
				@clearstatcache();
				if (!empty($data['image']) && is_file(PJ_INSTALL_PATH . $data['image']))
				{
					@unlink(PJ_INSTALL_PATH . $data['image']);
				}
			}
			
			$pjMultiLangModel->reset()->where('model', 'pjBanner')->whereIn('foreign_id', $_POST['record'])->eraseAll();
			pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Banner(s) have been deleted.'));
		}
		exit;
	}
	
	public function pjActionStatusBanner()
	{
		$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')))
			{
				pjBannerModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array('status' => $_GET['status']));
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Banner(s) have been modified.'));
			}
			pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing, empty or invalid parameters.'));
		}
		exit;
	}
	
	public function pjActionGetBanner()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			$pjBannerModel = pjBannerModel::factory()
				->join('pjMultiLang', sprintf("t2.model='pjBanner' AND t2.foreign_id=t1.id AND t2.locale='%u' AND t2.field='alt'", $this->getLocaleId()), 'left outer')
				->join('pjMultiLang', sprintf("t3.model='pjBanner' AND t3.foreign_id=t1.id AND t3.locale='%u' AND t3.field='title'", $this->getLocaleId()), 'left outer')
				->join('pjMultiLang', sprintf("t4.model='pjBanner' AND t4.foreign_id=t1.id AND t4.locale='%u' AND t4.field='url'", $this->getLocaleId()), 'left outer')
				->join('pjMultiLang', sprintf("t5.model='pjBanner' AND t5.foreign_id=t1.id AND t5.locale='%u' AND t5.field='code'", $this->getLocaleId()), 'left outer')
				->join('pjMultiLang', sprintf("t6.model='pjBanner' AND t6.foreign_id=t1.id AND t6.locale='%u' AND t6.field='image'", $this->getLocaleId()), 'left outer')
			;
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = $pjBannerModel->escapeString($_GET['q']);
				$q = str_replace(array('%', '_'), array('\%', '\_'), trim($q));
				$pjBannerModel->where(sprintf("(t4.content LIKE '%1\$s' OR t5.content LIKE '%1\$s' OR t2.content LIKE '%1\$s' OR t3.content LIKE '%1\$s')", "%$q%"));
			}
			
			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('T', 'F')))
			{
				$pjBannerModel->where('t1.status', $_GET['status']);
			}

			$column = 't1.id';
			$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 = $pjBannerModel->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 = $pjBannerModel
				->select('t1.*, t2.content AS `alt`, t3.content AS `title`, t5.content AS `code`, t6.content AS `image`')
				->orderBy("$column $direction")->limit($rowCount, $offset)->findAll()->getData();
			foreach($data as $k=> $v)
			{
				$v['code'] = pjSanitize::html($v['code']);
				$data[$k] = $v;
			}
			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('pjAdminBanners.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveBanner()
	{
		$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.'));
			}
			$pjBannerModel = pjBannerModel::factory();
			if (!in_array($_POST['column'], $pjBannerModel->getI18n()))
			{
				$pjBannerModel->set('id', $_GET['id'])->modify(array($_POST['column'] => $_POST['value']));
			} else {
				pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($_POST['column'] => $_POST['value'])), $_GET['id'], 'pjBanner');
			}
			pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Banner have been modified.'));
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();

		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['banner_update']))
			{
				$pjBannerModel = pjBannerModel::factory();
				$arr = $pjBannerModel->find($_POST['id'])->getData();
				if (empty($arr))
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminBanners&action=pjActionIndex&err=ABR08");
				}

				$data = array();
				$data['type'] = $_POST['type'];
				switch ($_POST['type'])
				{
					case 'image':
						if (isset($_FILES['image']))
						{
							$files = array();
							foreach ($_FILES['image']['tmp_name'] as $locale_id => $tmp_name)
							{
								$files[$locale_id] = array(
									'name' => $_FILES['image']['name'][$locale_id],
									'type' => $_FILES['image']['type'][$locale_id],
									'tmp_name' => $_FILES['image']['tmp_name'][$locale_id],
									'error' =>  $_FILES['image']['error'][$locale_id],
									'size' => $_FILES['image']['size'][$locale_id]
								);
							}
							
							$upload = new pjUpload();
							$upload->setAllowedExt($this->imageExt);
							$upload->setAllowedTypes($this->imageType);
							
							foreach ($files as $locale_id => $file)
							{
								if ($upload->load($file))
								{
									$dest = PJ_UPLOAD_PATH . 'banners/' . $arr['id'] .'_'. md5(uniqid(rand(), true)) . '.' . $upload->getExtension();
									if ($upload->save($dest))
									{
										$_POST['i18n'][$locale_id]['image'] = $dest;
										//TODO unlink old banners(same id)
									}
								}
							}
						}
						$data['target'] = $_POST['target'];
						break;
					case 'code':
						$data['image'] = ':NULL';
						$data['target'] = ':NULL';
						if (!empty($arr['image']) && is_file(PJ_INSTALL_PATH . $arr['image']))
						{
							@unlink(PJ_INSTALL_PATH . $arr['image']);
						}
						break;
				}
				
				$pjBannerModel->set('id', $_POST['id'])->modify($data);
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjBanner');
				}
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminBanners&action=pjActionIndex&err=ABR01");
			}
			
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$arr = pjBannerModel::factory()->find($_GET['id'])->getData();
				if (empty($arr))
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminBanners&action=pjActionIndex&err=ABR08");
				}
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjBanner');
				$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->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('pjAdminBanners.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			} else {
				pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminBanners&action=pjActionIndex&err=ABR08");
			}
		} else {
			$this->set('status', 2);
		}
	}
}
?>