<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminJobs extends pjAdmin
{
	public function pjActionCheckRefId()
	{
		$this->setAjax(true);

		
		if ($this->isXHR() && isset($_GET['job_refid']))
		{
			$pjJobModel = pjJobModel::factory();
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$pjJobModel->where('t1.id !=', $_GET['id']);
			}
			echo $pjJobModel->where('t1.job_refid', $_GET['job_refid'])->findCount()->getData() == 0 ? 'true' : 'false';
		}
		exit;
	}
	
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || ($this->isEmployer() && $this->option_arr['o_is_adding_job_allowed'] == 'Yes'))
		{
			if (isset($_POST['job_create']))
			{
				$data = array();
				if ($_POST['status'] == 'E')
				{
					$data['expired'] = pjUtil::formatDate($_POST['expired'], $this->option_arr['o_date_format']);
				}else{
					$data['expired'] = ":NULL";
				}
				if(isset($_POST['expired_show']) && $_POST['status'] == 'E')
				{
					$data['expired_show'] = 'T';
				}else{
					$data['expired_show'] = 'F';
				}
				$data['last_extend'] = 'free';
				if ($this->isEmployer())
				{
					$data['employer_id'] = $this->getUserId();
					$data['status'] = 'E';
					$data['is_featured'] = 'F';
					$data['expired'] = date("Y-m-d", strtotime("-1 day"));
				}
				
				$data = array_merge($_POST, $data);
				$pjJobModel = pjJobModel::factory();
				if (!$pjJobModel->validates($data))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminJobs&action=pjActionCreate&err=1");
				}
				$id = pjJobModel::factory(array_merge($_POST, $data))->insert()->getInsertId();
				
				if ($id !== false && (int) $id > 0)
				{
					$err = 'AJ03';
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjJob');
					}
					
					if ($this->isEmployer())
					{
						$notify_id = 3;
						$notify_arr = pjNotificationModel::factory()->find($notify_id)->getData();
						$notify_arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($notify_id, 'pjNotification');
						
						$subject = $notify_arr['i18n'][$this->getLocaleId()]['subject'.$notify_id];
						$message = $notify_arr['i18n'][$this->getLocaleId()]['message'.$notify_id];
						
						$ref_id = $_POST['job_refid'];
						$edit_url = PJ_INSTALL_URL . "index.php?controller=pjAdminJobs&action=pjActionUpdate&id=$id&tab_id=tabs-2";
						

						$message = str_replace(array('{refid}', '{editjoburl}'), array($ref_id, $edit_url), $message);
						
						$from = $this->getFromEmail($this->option_arr);
						$to_arr = $this->getAdminEmail();
												
						$pjEmail = new pjEmail();
						if ($this->option_arr['o_send_email'] == 'smtp')
						{
							$pjEmail
										->setTransport('smtp')
										->setSmtpHost($this->option_arr['o_smtp_host'])
										->setSmtpPort($this->option_arr['o_smtp_port'])
										->setSmtpUser($this->option_arr['o_smtp_user'])
										->setSmtpPass($this->option_arr['o_smtp_pass'])
										->setSender($this->option_arr['o_smtp_user'])
									;
						}
						
						$pjEmail->setContentType('text/html');
						$pjEmail->setFrom($from);
						$pjEmail->setSubject($subject);
						foreach($to_arr as $to)
						{
							$pjEmail->setTo($to);
							$pjEmail->send($message);
						}
						
					}
				} else {
					$err = 'AJ04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminJobs&action=pjActionUpdate&id=$id&err=$err&tab_id=tabs-2");
			} 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']; //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));
				
				$type_arr = pjTypeModel::factory()->select('t1.*, t2.content AS name')
								->join('pjMultiLang', "t2.model='pjType' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
								->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
				$this->set('type_arr', pjSanitize::clean($type_arr));
				
				$category_arr = pjCategoryModel::factory()->select('t1.*, t2.content AS name')
								->join('pjMultiLang', "t2.model='pjCategory' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
								->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
				$this->set('category_arr', pjSanitize::clean($category_arr));
				
				if ($this->isEmployer())
				{
					$this->set('period_arr', pjPeriodModel::factory()->orderBy('t1.days ASC')->findAll()->getData());
				}
				
				$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('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminJobs.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteJob()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if ($_GET['id'])
			{
				$valid = true;
				if($this->isEmployer())
				{
					$job_id_arr = $this->getJobId($this->getUserId());
					if(!in_array($_GET['id'], $job_id_arr))
					{
						$valid = false;
					}
				}
				
				if($valid == true)
				{
					if (pjJobModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
					{
						pjMultiLangModel::factory()->where('model', 'pjJob')->where('foreign_id', $_GET['id'])->eraseAll();
	
						$response['code'] = 200;
					} else {
						$response['code'] = 100;
					}
				}else{
					$response['code'] = 100;
				}
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteJobBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjJobModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
				pjMultiLangModel::factory()->where('model', 'pjJob')->whereIn('foreign_id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionExportJob()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjJobModel::factory()->whereIn('id', $_POST['record'])->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Jobs-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionGetJob()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjJobModel = pjJobModel::factory()
				->join('pjMultiLang', sprintf("t2.model='pjJob' AND t2.foreign_id=t1.id AND t2.locale='%u' AND t2.field='address_city'", $this->getLocaleId()), 'left outer')
				->join('pjMultiLang', sprintf("t3.model='pjJob' AND t3.foreign_id=t1.id AND t3.locale='%u' AND t3.field='address_state'", $this->getLocaleId()), 'left outer');
			;
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = $pjJobModel->escapeStr($_GET['q']);
				$q = str_replace(array('_', '%'), array('\_', '\%'), trim($q));
				$pjJobModel->where('t1.job_refid LIKE', "%$q%");
			}
			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('T', 'F')))
			{
				if($_GET['status'] == 'T')
				{
					$pjJobModel->where("(t1.status = 'T' OR t1.expired >= CURDATE())");
				}else{
					$pjJobModel->where('t1.status', $_GET['status']);
				}
			}
			if (isset($_GET['refid']) && $_GET['refid'] != '')
			{
				$refid = $pjJobModel->escapeStr($_GET['refid']);
				$refid = str_replace(array('_', '%'), array('\_', '\%'), trim($refid));
				$pjJobModel->where("t1.job_refid LIKE '%$refid%'");
			}
			if (isset($_GET['keyword']) && $_GET['keyword'] != '')
			{
				$keyword = $pjJobModel->escapeStr($_GET['keyword']);
				$keyword = str_replace(array('_', '%'), array('\_', '\%'), trim($keyword));
				$pjJobModel->where("t1.id IN (SELECT t8.foreign_id FROM `".pjMultiLangModel::factory()->getTable()."` AS t8 WHERE t8.model='pjJob' AND t8.locale='".$this->getLocaleId()."' AND (t8.`field` = 'job_description' OR t8.`field` = 'job_title') AND t8.`content` LIKE '%$keyword%')");
			}
			if(!$this->isEmployer())
			{
				if (isset($_GET['employer_id']) && $_GET['employer_id'] != '')
				{
					$pjJobModel->where("t1.employer_id", $_GET['employer_id']);
				}
			}else{
				$pjJobModel->where("t1.employer_id", $this->getUserId());
			}
			if (isset($_GET['type_id']) && $_GET['type_id'] != '')
			{
				$pjJobModel->where("t1.type_id", $_GET['type_id']);
			}
			if (isset($_GET['category_id']) && $_GET['category_id'] != '')
			{
				$pjJobModel->where("t1.category_id", $_GET['category_id']);
			}
			if (isset($_GET['country_id']) && $_GET['country_id'] != '')
			{
				$pjJobModel->where("t1.country_id", $_GET['country_id']);
			}
			if (isset($_GET['address_state']) && $_GET['address_state'] != '')
			{
				$state = $pjJobModel->escapeStr($_GET['address_state']);
				$state = str_replace(array('_', '%'), array('\_', '\%'), trim($state));
				$pjJobModel->where("(t1.address_state LIKE '%$state%' OR t3.content LIKE '%$state%')");
			}
			if (isset($_GET['address_city']) && $_GET['address_city'] != '')
			{
				$city = $pjJobModel->escapeStr($_GET['address_city']);
				$city = str_replace(array('_', '%'), array('\_', '\%'), trim($city));
				$pjJobModel->where("(t1.address_city LIKE '%$city%' OR t2.content LIKE '%$city%')");
			}	
			$column = 'created';
			$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 = $pjJobModel->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 = $pjJobModel->select('t1.id, t1.job_refid, t1.expired, t1.status, 
					t5.content AS type_title, t7.content AS category, 
					(SELECT COUNT(*) FROM `'.pjApplicationModel::factory()->getTable().'` as t9 WHERE t9.job_id = t1.id) as cnt_applications')
				->join('pjType', 't4.id=t1.type_id', 'left outer')
				->join('pjMultiLang', "t5.model='pjType' AND t5.foreign_id=t4.id AND t5.field='name' AND t5.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjCategory', 't6.id=t1.category_id', 'left outer')
				->join('pjMultiLang', "t7.model='pjCategory' AND t7.foreign_id=t6.id AND t7.field='name' AND t7.locale='".$this->getLocaleId()."'", 'left outer')
				->orderBy("$column $direction")->limit($rowCount, $offset)->findAll()->getData();
			foreach($data as $k => $v)
			{
				if($v['status'] == 'T')
				{
					$v['expired'] = __('lblUnlimited', true);
				}else if($v['status'] == 'E'){
					$v['expired'] = date($this->option_arr['o_date_format'], strtotime($v['expired']));
				}else{
					$v['expired'] = '';
				}
				$data[$k] = $v;
			}	
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEmployer())
		{

			
			if(!$this->isEmployer())
			{
				$employer_arr = pjEmployerModel::factory()->orderBy("company_name ASC")->findAll()->getData();
			}else{
				$employer_arr = pjEmployerModel::factory()->find($this->getUserId())->getData();
			}
			
			$this->set('employer_arr', $employer_arr);
			
			$type_arr = pjTypeModel::factory()->select('t1.*, t2.content AS name')
							->join('pjMultiLang', "t2.model='pjType' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
							->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
			$this->set('type_arr', pjSanitize::clean($type_arr));
			
			$country_arr = pjCountryModel::factory()->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
					->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
			
			$category_arr = pjCategoryModel::factory()->select('t1.*, t2.content AS name')
								->join('pjMultiLang', "t2.model='pjCategory' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
								->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
			$this->set('category_arr', pjSanitize::clean($category_arr));
				
			$this->set('country_arr', $country_arr);

			$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'chosen/');
			$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminJobs.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}

	public function pjActionSaveJob()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjJobModel = pjJobModel::factory();
			if (!in_array($_POST['column'], $pjJobModel->i18n))
			{
				$data = array();
				if (in_array($_POST['column'], array('expired')))
				{
					$_POST['value'] = pjUtil::formatDate($_POST['value'], $this->option_arr['o_date_format']);
					$data[$_POST['column']] = $_POST['value'];
					$data['status'] = 'E';
				}else{
					$data[$_POST['column']] = $_POST['value'];
				}
				
				$pjJobModel->where('id', $_GET['id'])->limit(1)->modifyAll($data);
			} else {
				pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($_POST['column'] => $_POST['value'])), $_GET['id'], 'pjJob');
			}
		}
		exit;
	}
	
	public function pjActionStatusJob()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjJobModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array(
					'status' => ":IF(`status`='F','T','F')"
				));
			}
		}
		exit;
	}
	
	public function pjActionExtend()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEmployer())
		{
			if (isset($_POST['extend']))
			{
				$pjJobModel = pjJobModel::factory();
			
				$arr = $pjJobModel->find($_POST['id'])->getData();
				$period_arr = pjPeriodModel::factory()->find($_POST['period_id'])->getData();
				
				if (count($arr) > 0 && count($period_arr) > 0)
				{
					$current = time();
					if ($arr['last_extend'] == 'paid' && !empty($arr['expire']) && $arr['expire'] != '0000-00-00')
					{
						$current = strtotime($arr['expire']);
					}
					
					$pjJobModel->set('id', $arr['id'])->modify(array(
						'status' => 'E',
						'last_extend' => 'free',
						'expired' => date("Y-m-d", $current + (int) $period_arr['days'] * 86400)
					));
				}
			}
			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminJobs&action=pjActionIndex&err=AJ09");
			
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionPayment()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEmployer())
		{
			$arr = pjJobModel::factory()
				->select('t1.*, t2.content AS job_title')
				->join('pjMultiLang', "t2.model='pjJob' AND t2.foreign_id=t1.id AND t2.field='job_title' AND t2.locale='".$this->getLocaleId()."'", 'left')
				->find($_GET['id'])->getData();
				
			if (count($arr) === 0)
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminJobs&action=pjActionIndex&err=AL08");
			} elseif ($this->isEmployer() && $arr['employer_id'] != $this->getUserId()) {
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminJobs&action=pjActionIndex&err=AL09");
			}
			$this->set('arr', $arr);
			$this->set('period_arr', pjPeriodModel::factory()->orderBy('t1.days ASC')->findAll()->getData());
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEmployer())
		{
			if (isset($_POST['job_update']))
			{
				$data = array();
				
				if ($this->isEmployer())
				{
					$arr = pjJobModel::factory()->find($_POST['id'])->getData();
					if ($arr['employer_id'] != $this->getUserId())
					{
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminJobs&action=pjActionIndex&err=AJ09");
					}
					unset($_POST['employer_id']);
					$data['employer_id'] = $arr['employer_id'];
					$data['expired'] = $arr['expired'];
					$data['status'] = $arr['status'];
				}else{
					if ($_POST['status'] == 'E')
					{
						$data['expired'] = pjUtil::formatDate($_POST['expired'], $this->option_arr['o_date_format']);
					}else{
						$data['expired'] = ":NULL";
					}
				}
				if(isset($_POST['expired_show']) && $_POST['status'] == 'E')
				{
					$data['expired_show'] = 'T';
				}else{
					$data['expired_show'] = 'F';
				}

				if(!isset($_POST['employer_show']))
				{
					$data['employer_show'] = 'F';
				}
				$data['modified'] = date('Y-m-d H:i:s');
				
				pjJobModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll(array_merge($_POST, $data));
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjJob');
				}
				
				$pjJobFilterModel = pjJobFilterModel::factory();
				if(isset($_POST['filter_id']) && !empty($_POST['filter_id']))
				{
					$pjJobFilterModel->reset()->where('job_id', $_POST['id'])->eraseAll();
					$pjJobFilterModel->reset()->begin();
					foreach ($_POST['filter_id'] as $filter_id)
					{
						$data = array();
						$data['job_id'] = $_POST['id'];
						$data['filter_id'] = $filter_id;
						$pjJobFilterModel->reset()->setAttributes($data)->insert();
					}
					$pjJobFilterModel->commit();
				}
				
				$err = 'AJ01';
				pjUtil::redirect(sprintf("%s?controller=pjAdminJobs&action=pjActionUpdate&id=%u&locale=%u&tab_id=%s&err=%s", $_SERVER['PHP_SELF'], $_POST['id'], $_POST['locale'], $_POST['tab_id'], $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']; //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));
				
				$arr = pjJobModel::factory()->find($_GET['id'])->getData();
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjJob');
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminJobs&action=pjActionIndex&err=AJ08");
				}else{
					if($this->isEmployer())
					{
						if($arr['employer_id'] != $this->getUserId())
						{
							pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminJobs&action=pjActionIndex&err=AJ08");
						}
					}
				}
				
				$country_arr = pjCountryModel::factory()->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
					->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
					
				$employer_arr = pjEmployerModel::factory()->orderBy("company_name ASC")->findAll()->getData();

				$num_apps = pjApplicationModel::factory()->where('job_id', $_GET['id'])->findCount()->getData();
				
				$filter_arr = array();
				$_arr = pjFilterModel::factory()
					->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjFilter' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
					->where('status', 'T')
					->orderBy('t1.type ASC, t1.sort ASC')
					->findAll()
					->getData();
				foreach($_arr as $v)
				{
					$filter_arr[$v['type']][] = $v;
				}
				
				$this->set('type_arr', pjTypeModel::factory()->select('t1.*, t2.content AS name')
						->join('pjMultiLang', "t2.model='pjType' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'inner')
						->where('t1.status', 'T')->orderBy('name ASC')->findAll()->getData()
				);
				
				$category_arr = pjCategoryModel::factory()->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjCategory' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
					->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
				$this->set('category_arr', pjSanitize::clean($category_arr));
				
				$this->set('arr', $arr);
				$this->set('filter_arr', $filter_arr);
				$this->set('num_apps', $num_apps);
				$this->set('employer_arr', $employer_arr);
				$this->set('country_arr', pjSanitize::clean($country_arr));
				$this->set('filter_id_arr', pjJobFilterModel::factory()->where('job_id', $_GET['id'])->findAll()->getDataPair(null, 'filter_id'));
				
				# TinyMCE
				$this->appendJs('tinymce.min.js', PJ_THIRD_PARTY_PATH . 'tinymce/');
				
				$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('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminJobs.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetLocale()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_GET['locale']) && (int) $_GET['locale'] > 0)
			{
				pjAppController::setFields($_GET['locale']);

				
				$this->set('type_arr', pjTypeModel::factory()->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjType' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$_GET['locale']."'", 'inner')
					->where('t1.status', 'T')->orderBy('name ASC')->findAll()->getData()
				);
				
				$category_arr = pjCategoryModel::factory()->select('t1.*, t2.content AS name')
								->join('pjMultiLang', "t2.model='pjCategory' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
								->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
				$this->set('category_arr', pjSanitize::clean($category_arr));
			}
		}
	}
	
	public function pjActionExport()
	{
		$this->checkLogin();
	
		if ($this->isAdmin())
		{
			if(isset($_POST['jobs_export']))
			{
				$pjJobModel = pjJobModel::factory()
					->select('t1.*, t9.logo, t9.thumb, t9.company_name, t7.content AS job_title, t3.content AS type_title, t5.content AS category, t6.content AS country')
					->join('pjType', 't2.id=t1.type_id', 'left')
					->join('pjMultiLang', "t3.model='pjType' AND t3.foreign_id=t2.id AND t3.field='name' AND t3.locale='".$this->getLocaleId()."'", 'left')
					->join('pjCategory', 't4.id=t1.category_id', 'left')
					->join('pjMultiLang', "t5.model='pjCategory' AND t5.foreign_id=t4.id AND t5.field='name' AND t5.locale='".$this->getLocaleId()."'", 'left')
					->join('pjMultiLang', "t6.model='pjCountry' AND t6.foreign_id=t1.country_id AND t6.field='name' AND t6.locale='".$this->getLocaleId()."'", 'left')
					->join('pjMultiLang', "t7.model='pjJob' AND t7.foreign_id=t1.id AND t7.field='job_title' AND t7.locale='".$this->getLocaleId()."'", 'left')
					->join('pjMultiLang', "t8.model='pjJob' AND t8.foreign_id=t1.id AND t8.field='job_description' AND t8.locale='".$this->getLocaleId()."'", 'left')
					->join('pjEmployer', "t9.id=t1.employer_id AND t9.status='T'", 'left');
					
				$column = 't1.created';
				$direction = 'ASC';
				$where_str = pjUtil::getMadeWhere($_POST['made_period'], $this->option_arr['o_week_start']);
				if($where_str != '')
				{
					$pjJobModel->where($where_str);
				}
				if($this->isEmployer())
				{
					$pjJobModel->where("t1.employer_id", $this->getUserId());
				}
				$arr= $pjJobModel
					->orderBy("$column $direction")
					->findAll()
					->getData();
				if($_POST['type'] == 'file')
				{
					$this->setLayout('pjActionEmpty');
	
					if($_POST['format'] == 'csv')
					{
						$csv = new pjCSV();
						$csv
							->setHeader(true)
							->setName("Export-".time().".csv")
							->process($arr)
							->download();
					}
					if($_POST['format'] == 'xml')
					{
						$xml = new pjXML();
						$xml
						->setEncoding('UTF-8')
						->setName("Export-".time().".xml")
						->process($arr)
						->download();
					}
					exit;
				}else{
					$pjPasswordModel = pjPasswordModel::factory();
					$password = md5($_POST['password'].PJ_SALT);
					$arr = $pjPasswordModel
						->where("t1.password", $password)
						->where("t1.format", $_POST['format'])
						->where("t1.period", $_POST['made_period'])
						->limit(1)
						->findAll()
						->getData();
					if (count($arr) != 1)
					{
						$pjPasswordModel->setAttributes(array('password' => $password, 'user_id' => $this->isEmployer() ? $this->getUserId() : ':NULL','format' => $_POST['format'], 'period' => $_POST['made_period']))->insert();
					}
					$this->set('password', $password);
				}
			}
	
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
			$this->appendJs('pjAdminJobs.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionExportFeed()
	{
		$this->setLayout('pjActionEmpty');
		$access = true;
		$user_id = NULL;
		if(isset($_GET['p']))
		{
			$pjPasswordModel = pjPasswordModel::factory();
			$arr = $pjPasswordModel
				->where('t1.password', $_GET['p'])
				->where("t1.format", $_GET['format'])
				->where("t1.period", $_GET['period'])
				->limit(1)
				->findAll()
				->getData();
			if (count($arr) != 1)
			{
				$access = false;
			}
			$user_id = $arr[0]['user_id'];
		}
		if($access == true)
		{
			$arr = $this->pjGetFeedData($_GET, $user_id);
			if(!empty($arr))
			{
				if($_GET['format'] == 'xml')
				{
					$xml = new pjXML();
					echo $xml
						->setEncoding('UTF-8')
						->process($arr)
						->getData();
	
				}
				if($_GET['format'] == 'csv')
				{
					$csv = new pjCSV();
					echo $csv
						->setHeader(true)
						->process($arr)
						->getData();
	
				}
			}
		}else{
			__('lblNoAccessToFeed');
		}
		exit;
	}
	public function pjGetFeedData($get, $user_id)
	{
		$arr = array();
		$status = true;
		$period = '';
		if(isset($get['period']))
		{
			if(!ctype_digit($get['period']))
			{
				$status = false;
			}else{
				$period = $get['period'];
			}
		}else{
			$status = false;
		}
	
		if($status == true && $period != '')
		{
			$pjJobModel = pjJobModel::factory()
				->select('t1.*, t9.logo, t9.thumb, t9.company_name, t7.content AS job_title, t3.content AS type_title, t5.content AS category, t6.content AS country')
				->join('pjType', 't2.id=t1.type_id', 'left')
				->join('pjMultiLang', "t3.model='pjType' AND t3.foreign_id=t2.id AND t3.field='name' AND t3.locale='".$this->getLocaleId()."'", 'left')
				->join('pjCategory', 't4.id=t1.category_id', 'left')
				->join('pjMultiLang', "t5.model='pjCategory' AND t5.foreign_id=t4.id AND t5.field='name' AND t5.locale='".$this->getLocaleId()."'", 'left')
				->join('pjMultiLang', "t6.model='pjCountry' AND t6.foreign_id=t1.country_id AND t6.field='name' AND t6.locale='".$this->getLocaleId()."'", 'left')
				->join('pjMultiLang', "t7.model='pjJob' AND t7.foreign_id=t1.id AND t7.field='job_title' AND t7.locale='".$this->getLocaleId()."'", 'left')
				->join('pjMultiLang', "t8.model='pjJob' AND t8.foreign_id=t1.id AND t8.field='job_description' AND t8.locale='".$this->getLocaleId()."'", 'left')
				->join('pjEmployer', "t9.id=t1.employer_id AND t9.status='T'", 'left');
	
			$column = 't1.created';
			$direction = 'DESC';
			$where_str = pjUtil::getMadeWhere($period, $this->option_arr['o_week_start']);
			if($where_str != '')
			{
				$pjJobModel->where($where_str);
			}
			if((int) $user_id > 0)
			{
				$pjJobModel->where("t1.employer_id", $user_id);
			}
			$arr= $pjJobModel
				->orderBy("$column $direction")
				->findAll()
				->getData();
		}
		return $arr;
	}
	
	public function pjActionGetPassword()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjPasswordModel = pjPasswordModel::factory();
	
			$column = 'id';
			$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 = $pjPasswordModel->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 = $pjPasswordModel->select("t1.*")->orderBy("$column $direction")->limit($rowCount, $offset)->findAll()->getData();
	
			$export_formats = __('export_formats', true, false);
			$made_arr = __('made_arr', true, false);
			foreach($data as $k => $v)
			{
				$v['params'] = '&format=' . $v['format'] . '&period=' . $v['period'] . '&p=' . $v['password'];
	
				$v['period'] = $made_arr[$v['period']];
				$v['format'] = $export_formats[$v['format']];
				$data[$k] = $v;
			}
	
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	public function pjActionDeletePassword()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if (pjPasswordModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeletePasswordBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjPasswordModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
}
?>