<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminFilters extends pjAdmin
{
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			if (isset($_POST['filter_create']))
			{
				$data = array();
				$data['sort'] = $this->getLastOrder($_POST['type']);
				$id = pjFilterModel::factory(array_merge($_POST, $data))->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$err = 'AFT03';
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjFilter');
					}
				} else {
					$err = 'AFT04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminFilters&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('pjAdminFilters.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			}
		} else {
			$this->set('status', 2);
		}
	}
		
	public function pjActionDeleteFilter()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if (pjFilterModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				pjMultiLangModel::factory()->where('model', 'pjFilter')->where('foreign_id', $_GET['id'])->eraseAll();
				pjJobFilterModel::factory()->where('job_id', $_GET['id'])->eraseAll();
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteFilterBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjFilterModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
				pjMultiLangModel::factory()->where('model', 'pjFilter')->whereIn('foreign_id', $_POST['record'])->eraseAll();
				pjJobFilterModel::factory()->whereIn('job_id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionGetFilter()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjFilterModel = pjFilterModel::factory()->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjFilter' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left');
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = $pjFilterModel->escapeStr($_GET['q']);
				$q = str_replace(array('%', '_'), array('\%', '\_'), trim($q));
				$pjFilterModel->where('t2.content LIKE', "%$q%");
			}

			if(isset($_GET['type']) && $_GET['type'] != '')
			{
				$pjFilterModel->where('t1.type', $_GET['type']);
			}
			
			$column = 't1.type ASC, 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 = $pjFilterModel->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 = $pjFilterModel
				->select('t1.*, t2.content AS name')
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();
			$filter_types = __('filter_types', true);
			foreach($data as $k => $v)
			{
				$v['type'] = $filter_types[$v['type']];
				$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('pjAdminFilters.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveFilter()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjFilterModel = pjFilterModel::factory();
			if (!in_array($_POST['column'], $pjFilterModel->i18n))
			{
				$pjFilterModel->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
			} else {
				$pjMultiLangModel = pjMultiLangModel::factory();
				$cnt = $pjMultiLangModel	
							->where('t1.foreign_id !=', $_GET['id'])
							->where('t1.model', 'pjFilter')
							->where('t1.locale', $this->getLocaleId())
							->where('t1.field', 'name')
							->where('t1.content', $_POST['value'])
							->findCount()->getData();
							
				if($cnt == 0)
				{
					$pjMultiLangModel->reset()->updateMultiLang(array($this->getLocaleId() => array($_POST['column'] => $_POST['value'])), $_GET['id'], 'pjFilter');
				}
			}
		}
		exit;
	}
	
	public function pjActionSortFilter()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjFilterModel = new pjFilterModel();
			if(isset($_GET['type']) && $_GET['type'] != '')
			{
				$pjFilterModel->where('t1.type', $_GET['type']);
			}
			$arr = $pjFilterModel->whereIn('id', $_POST['sort'])->orderBy("t1.sort ASC")->findAll()->getDataPair('id', 'sort');
			$fliped = array_flip($_POST['sort']);
			$combined = array_combine(array_keys($fliped), $arr);
			$pjFilterModel->begin();
			foreach ($combined as $id => $sort)
			{
				$pjFilterModel->setAttributes(compact('id'))->modify(compact('sort'));
			}
			$pjFilterModel->commit();
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();

		if ($this->isAdmin())
		{
			if (isset($_POST['filter_update']))
			{
				pjFilterModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll($_POST);
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjFilter');
				}
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminFilters&action=pjActionIndex&err=AFT01");
				
			} else {
				$arr = pjFilterModel::factory()->find($_GET['id'])->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminFilters&action=pjActionIndex&err=AFT08");
				}
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjFilter');
				$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('pjAdminFilters.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	private function getLastOrder($type)
	{
		$order = 1;
		$arr = pjFilterModel::factory()->where('t1.type', $type)->limit(1)->orderBy('t1.sort DESC')->findAll()->getData();
		if(!empty($arr))
		{
			$order = $arr[0]['sort'] + 1;
		}
		return $order;
	}
}
?>