<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminEmployers extends pjAdmin
{
	public function pjActionCheckEmail()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (!isset($_GET['email']) || empty($_GET['email']))
			{
				echo 'false';
				exit;
			}
			$pjEmployerModel = pjEmployerModel::factory()->where('t1.email', $_GET['email']);
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$pjEmployerModel->where('t1.id !=', $_GET['id']);
			}
			echo $pjEmployerModel->findCount()->getData() == 0 ? 'true' : 'false';
		}
		exit;
	}
	
	public function pjActionProfile()
	{
		$this->checkLogin();
		if ($this->isEmployer())
		{
			$id = $this->getUserId();
			
			if (isset($_POST['profile_update']))
			{
				$pjEmployerModel = pjEmployerModel::factory();
				
				$pjEmployerModel->where('id', $_POST['id'])->limit(1)->modifyAll($_POST);
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjEmployer');
				}
				if (isset($_FILES['company_logo']) && !empty($_FILES['company_logo']['tmp_name']))
				{
					$arr = $pjEmployerModel->reset()->find($_POST['id'])->getData();
					if (!empty($arr['logo']) && is_file(PJ_INSTALL_PATH . $arr['logo']))
					{
						@unlink(PJ_INSTALL_PATH . $arr['logo']);
					}
					if (!empty($arr['thumb']) && is_file(PJ_INSTALL_PATH . $arr['thumb']))
					{
						@unlink(PJ_INSTALL_PATH . $arr['thumb']);
					}
					
					$Image = new pjImage();
					$Image->setAllowedTypes(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg'));
					
					if ($Image->load($_FILES['company_logo']))
					{
						$resp = $Image->isConvertPossible();
						if ($resp['status'] === true)
						{
							$d = array();
							$hash = md5(uniqid(rand(), true));
							$thumb_path = PJ_UPLOAD_PATH . 'logos/thumbs/' . $_POST['id'] . '_' . $hash . '.' . $Image->getExtension();
							$logo_path = PJ_UPLOAD_PATH . 'logos/' . $_POST['id'] . '_' . $hash . '.' . $Image->getExtension();
					
							$Image->loadImage();
							$Image->saveImage($logo_path);
							
							$Image->loadImage($_FILES['company_logo']['tmp_name']);
							$Image->resizeSmart(300, 225);
							$Image->saveImage($thumb_path);
								
							$d['thumb'] = $thumb_path;
							$d['logo'] = $logo_path;
					
							$pjEmployerModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll($d);
						}
					}
				}
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEmployers&action=pjActionProfile&err=AP01");
			}else{
			
				$arr = pjEmployerModel::factory()->find($id)->getData();
				
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjEmployer');
				$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']; //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.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('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('additional-methods.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminEmployers.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			if (isset($_POST['employer_create']))
			{
				$pjEmployerModel = pjEmployerModel::factory();
				
				$data = array();
				$data['ip_registered'] = pjUtil::getClientIp();
				$id = $pjEmployerModel->setAttributes(array_merge($_POST, $data))->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					if (isset($_FILES['company_logo']) && !empty($_FILES['company_logo']['tmp_name']))
					{
						$Image = new pjImage();
						$Image->setAllowedTypes(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg'));
							
						if ($Image->load($_FILES['company_logo']))
						{
							$resp = $Image->isConvertPossible();
							if ($resp['status'] === true)
							{
								$d = array();
								$hash = md5(uniqid(rand(), true));
								$thumb_path = PJ_UPLOAD_PATH . 'logos/thumbs/' . $id . '_' . $hash . '.' . $Image->getExtension();
								$logo_path = PJ_UPLOAD_PATH . 'logos/' . $id . '_' . $hash . '.' . $Image->getExtension();
									
								$Image->loadImage();
								$Image->saveImage($logo_path);
								
								$Image->loadImage($_FILES['company_logo']['tmp_name']);
								$Image->resizeSmart(300, 225);
								$Image->saveImage($thumb_path);
									
								$d['thumb'] = $thumb_path;
								$d['logo'] = $logo_path;
									
								$pjEmployerModel->reset()->where('id', $id)->limit(1)->modifyAll($d);
							}
						}
					}
					$err = 'AER03';
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjEmployer');
					}
				} else {
					$err = 'AER04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminEmployers&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']; //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.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('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('additional-methods.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminEmployers.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteEmployer()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if ($_GET['id'])
			{
				$pjEmployerModel = pjEmployerModel::factory();
				$arr = $pjEmployerModel->find($_GET['id'])->getData();
				if(!empty($arr))
				{
					if ($pjEmployerModel->reset()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
					{
						pjMultiLangModel::factory()->where('model', 'pjEmployer')->where('foreign_id', $_GET['id'])->eraseAll();
						
						if (!empty($arr['logo']) && is_file(PJ_INSTALL_PATH . $arr['logo']))
						{
							@unlink(PJ_INSTALL_PATH . $arr['logo']);
						}
						if (!empty($arr['thumb']) && is_file(PJ_INSTALL_PATH . $arr['thumb']))
						{
							@unlink(PJ_INSTALL_PATH . $arr['thumb']);
						}
							
						$response['code'] = 200;
					} else {
						$response['code'] = 100;
					}
				}else{
					$response['code'] = 100;
				}
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteEmployerBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				$pjEmployerModel = pjEmployerModel::factory();
				$arr = $pjEmployerModel->whereIn('id', $_POST['record'])->findAll()->getData();
				if(!empty($arr))
				{
					foreach($arr as $v)
					{
						if (!empty($v['logo']) && is_file(PJ_INSTALL_PATH . $v['logo']))
						{
							@unlink(PJ_INSTALL_PATH . $v['logo']);
						}
						if (!empty($v['thumb']) && is_file(PJ_INSTALL_PATH . $v['thumb']))
						{
							@unlink(PJ_INSTALL_PATH . $v['thumb']);
						}
					}
					pjEmployerModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
					pjMultiLangModel::factory()->where('model', 'pjEmployer')->whereIn('foreign_id', $_POST['record'])->eraseAll();
				}
			}
		}
		exit;
	}
	
	public function pjActionExportEmployer()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjEmployerModel::factory()->whereIn('id', $_POST['record'])->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Employers-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionGetEmployer()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjEmployerModel = pjEmployerModel::factory();
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = $pjEmployerModel->escapeStr($_GET['q']);
				$q = str_replace(array('%', '_'), array('\%', '\_'), trim($q));
				$pjEmployerModel->where('t1.email LIKE', "%$q%");
				$pjEmployerModel->orWhere('t1.company_name LIKE', "%$q%");
				$pjEmployerModel->orWhere('t1.contact_name LIKE', "%$q%");
			}

			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('T', 'F')))
			{
				$pjEmployerModel->where('t1.status', $_GET['status']);
			}
				
			$column = 'company_name';
			$direction = 'ASC';
			$allowed_columns = array('company_name', 'email', 'cnt_jobs', 'cnt_apps', 'status');
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array($_GET['column'], $allowed_columns) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}

			$total = $pjEmployerModel->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 = $pjEmployerModel
				->select("t1.id, t1.email, t1.company_name, DATE(t1.created) AS created, t1.status,
						  (SELECT COUNT(TJ.id) FROM `".pjJobModel::factory()->getTable()."` AS TJ WHERE TJ.employer_id=t1.id) AS cnt_jobs,
						  (SELECT COUNT(TA.id) FROM `".pjApplicationModel::factory()->getTable()."` AS TA WHERE TA.job_id IN (SELECT TJ.id FROM `".pjJobModel::factory()->getTable()."` AS TJ WHERE TJ.employer_id=t1.id) ) AS cnt_apps")
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();

			$data = pjSanitize::clean($data);
			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('pjAdminEmployers.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}

	public function pjActionSaveEmployer()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjEmployerModel = pjEmployerModel::factory();
			if (!in_array($_POST['column'], $pjEmployerModel->i18n))
			{
				$pjEmployerModel->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
			} else {
				pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($_POST['column'] => $_POST['value'])), $_GET['id'], 'pjEmployer');
			}
		}
		exit;
	}
	
	public function pjActionStatusEmployer()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjEmployerModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array(
					'status' => ":IF(`status`='F','T','F')"
				));
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
				
			if (isset($_POST['employer_update']))
			{
				$pjEmployerModel = pjEmployerModel::factory();
				
				$pjEmployerModel->where('id', $_POST['id'])->limit(1)->modifyAll($_POST);
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjEmployer');
				}
				if (isset($_FILES['company_logo']) && !empty($_FILES['company_logo']['tmp_name']))
				{
					$arr = $pjEmployerModel->reset()->find($_POST['id'])->getData();
					if (!empty($arr['logo']) && is_file(PJ_INSTALL_PATH . $arr['logo']))
					{
						@unlink(PJ_INSTALL_PATH . $arr['logo']);
					}
					if (!empty($arr['thumb']) && is_file(PJ_INSTALL_PATH . $arr['thumb']))
					{
						@unlink(PJ_INSTALL_PATH . $arr['thumb']);
					}
					
					$Image = new pjImage();
					$Image->setAllowedTypes(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg'));
						
					if ($Image->load($_FILES['company_logo']))
					{
						$resp = $Image->isConvertPossible();
						if ($resp['status'] === true)
						{
							$d = array();
							$hash = md5(uniqid(rand(), true));
							$thumb_path = PJ_UPLOAD_PATH . 'logos/thumbs/' . $_POST['id'] . '_' . $hash . '.' . $Image->getExtension();
							$logo_path = PJ_UPLOAD_PATH . 'logos/' . $_POST['id'] . '_' . $hash . '.' . $Image->getExtension();
							
							$Image->loadImage();
							$Image->saveImage($logo_path);
							
							$Image->loadImage($_FILES['company_logo']['tmp_name']);
							$Image->resizeSmart(73, 73);
							$Image->saveImage($thumb_path);
								
							$d['thumb'] = $thumb_path;
							$d['logo'] = $logo_path;
								
							$pjEmployerModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll($d);
						}
					}
				}
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEmployers&action=pjActionIndex&err=AER01");
				
			} else {
				$arr = pjEmployerModel::factory()
					->select("t1.*, AES_DECRYPT(t1.password, '".PJ_SALT."') AS `password`,
							  (SELECT COUNT(TJ.id) FROM `".pjJobModel::factory()->getTable()."` AS TJ WHERE TJ.employer_id=t1.id) AS cnt_jobs,
							  (SELECT COUNT(TJ.id) FROM `".pjJobModel::factory()->getTable()."` AS TJ WHERE TJ.employer_id=t1.id AND (TJ.status='T' OR (TJ.status='E' AND TJ.expired >= CURDATE() ) ) ) AS cnt_active_jobs")
					->find($_GET['id'])
					->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminEmployers&action=pjActionIndex&err=AER08");
				}
				
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjEmployer');
				$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.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('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('additional-methods.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminEmployers.js');
			}
		} else {
			$this->set('status', 2);
		}
	}

	public function pjActionDeleteLogo()
	{
		$this->setAjax(true);
		
		$pjEmployerModel = pjEmployerModel::factory();
		
		$arr = $pjEmployerModel->find($_POST['id'])->getData();
		
		$json_arr = array();
		if(!empty($arr))
		{
			$d['logo'] = ':NULL';
			$d['thumb'] = ':NULL';
			$pjEmployerModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll($d);
			
			if (!empty($arr['logo']) && is_file(PJ_INSTALL_PATH . $arr['logo']))
			{
				@unlink(PJ_INSTALL_PATH . $arr['logo']);
			}
			if (!empty($arr['thumb']) && is_file(PJ_INSTALL_PATH . $arr['thumb']))
			{
				@unlink(PJ_INSTALL_PATH . $arr['thumb']);
			}
			$json_arr['status'] = 1;
			
		}else{
			$json_arr['status'] = 0;
		}
		pjAppController::jsonResponse($json_arr);		
	}
}
?>