<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}

class pjLoad extends pjFront
{
	private $isoDatePattern = '/\d{4}-\d{2}-\d{2}/';
	
	public function pjActionCheckEmail()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (!isset($_GET['email']) || empty($_GET['email']))
			{
				echo 'false';
				exit;
			}
			if($_GET['pjType'] == 'Employer')
			{
				$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';
			}else{
				$pjEmployeeModel = pjEmployeeModel::factory()->where('t1.email', $_GET['email']);
				if (isset($_GET['id']) && (int) $_GET['id'] > 0)
				{
					$pjEmployeeModel->where('t1.id !=', $_GET['id']);
				}
				echo $pjEmployeeModel->findCount()->getData() == 0 ? 'true' : 'false';
			}
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$path = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
		$path = $path == '/' ? '' : $path;
		if ($this->option_arr['o_seo_url'] == 'No')
		{
			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionJobs");
		}else{
			if(empty($this->option_arr['o_job_page']))
			{
				pjUtil::redirect($path . "/job-home.html");
			}
		}
	}
	
	public function pjActionJobs()
	{
		if(isset($_GET['linkedin']) && isset($_SESSION[$this->defaultUser]) && $_SESSION[$this->defaultUser]['is_employer'] == true)
		{
			pjUtil::redirect(PJ_INSTALL_URL . 'index.php?controller=pjAdmin&action=pjActionJobs');
		}
		
		$employer_table = pjEmployerModel::factory()->getTable();
		
		$pjJobModel = pjJobModel::factory()
			->select('t1.*, t9.logo, t9.thumb, t9.company_name, t7.content AS job_title, 
					t8.content AS job_description, t3.content AS type_title, 
					t5.content AS category, t6.content AS country,
					t10.content AS lang_address, t11.content AS lang_city, t12.content AS lang_state')
			->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')
			->join('pjMultiLang', "t10.model='pjJob' AND t10.foreign_id=t1.id AND t10.field='address_content' AND t10.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t11.model='pjJob' AND t11.foreign_id=t1.id AND t11.field='address_city' AND t11.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t12.model='pjJob' AND t12.foreign_id=t1.id AND t12.field='address_state' AND t12.locale='".$this->getLocaleId()."'", 'left');
		
		$pjJobModel->where("(t1.status = 'T' OR (t1.status = 'E' AND t1.expired >= CURDATE()))");
		$pjJobModel->where("t1.category_id IN (SELECT `TC`.`id` FROM `".pjCategoryModel::factory()->getTable()."` as `TC` WHERE `TC`.`status` ='T')");
		$pjJobModel->where("t1.type_id IN (SELECT `TT`.`id` FROM `".pjTypeModel::factory()->getTable()."` as `TT` WHERE `TT`.`status` ='T')");
		$pjJobModel->where("t1.employer_id IN (SELECT `TE`.`id` FROM `".$employer_table."` as `TE` WHERE `TE`.`status` ='T')");
		
		$has_filter = false;
		
		if (isset($_GET['refid']))
		{
			if($_GET['refid'] != '')
			{
				$refid = $pjJobModel->escapeStr($_GET['refid']);
				$refid = str_replace(array('%', '_'), array('\%', '\_'), trim($refid));
				$pjJobModel->where("t1.job_refid LIKE '%$refid%'");
				$has_filter = true;
			}
		}
		if (isset($_GET['keyword']))
		{
			if($_GET['keyword'] != '')
			{
				$keyword = $pjJobModel->escapeStr($_GET['keyword']);
				$keyword = str_replace(array('%', '_'), array('\%', '\_'), trim($keyword));
				$pjJobModel->where(sprintf("(t1.job_refid LIKE '%1\$s' OR t7.content LIKE '%1\$s' OR t8.content LIKE '%1\$s' OR t9.company_name LIKE '%1\$s')", 
					"%$keyword%"));
				$has_filter = true;
			}
		}
		if (isset($_GET['type_id']) && count($_GET['type_id']) > 0)
		{
			$pjJobModel->whereIn("t1.type_id", $_GET['type_id']);
			$has_filter = true;
		}
		if (isset($_GET['category_id']) && count($_GET['category_id']) > 0)
		{
			$pjJobModel->whereIn("t1.category_id", $_GET['category_id']);
			$has_filter = true;
		}
		if (isset($_GET['employer_id']) && count($_GET['employer_id']) > 0)
		{
			$pjJobModel->whereIn("t1.employer_id", $_GET['employer_id']);
			$has_filter = true;
		}
		if (isset($_GET['filter_id']) && count($_GET['filter_id']) > 0)
		{
			$pjJobModel->where("t1.id IN (SELECT TJF.job_id FROM `".pjJobFilterModel::factory()->getTable()."` AS TJF WHERE TJF.filter_id IN (".join(",", $_GET['filter_id']).") )");
			$has_filter = true;
		}
		if (isset($_GET['country_id']))
		{
			if($_GET['country_id'] != '')
			{
				$country_id = $pjJobModel->escapeStr($_GET['country_id']);
				$pjJobModel->where("t1.country_id", $country_id);
				$has_filter = true;
			}
		}
		if (isset($_GET['company_name']))
		{
			if($_GET['company_name'] != '')
			{
				$company_name = $pjJobModel->escapeStr($_GET['company_name']);
				$pjJobModel->where("(t1.employer_id IN(SELECT `TE`.`id` FROM `".pjEmployerModel::factory()->getTable()."` AS `TE` WHERE `TE`.company_name LIKE '%$company_name%'))");
				$has_filter = true;
			}
		}
		if (isset($_GET['address_state']))
		{
			if($_GET['address_state'] != '')
			{
				$state = $pjJobModel->escapeStr($_GET['address_state']);
				$state = str_replace(array('%', '_'), array('\%', '\_'), trim($state));
				$pjJobModel->where("(t1.address_state LIKE '%$state%' OR t12.content LIKE '%$state%')");
				$has_filter = true;
			}
		}
		if (isset($_GET['address_city']))
		{
			if($_GET['address_city'] != '')
			{
				$city = $pjJobModel->escapeStr($_GET['address_city']);
				$city = str_replace(array('%', '_'), array('\%', '\_'), trim($city));
				$pjJobModel->where("(t1.address_city LIKE '%$city%' OR t11.content LIKE '%$city%')");
				$has_filter = true;
			}
		}
		
		if (isset($_GET['location']))
		{
			if($_GET['location'] != '')
			{
				$location = $pjJobModel->escapeStr($_GET['location']);
				$location = str_replace(array('%', '_'), array('\%', '\_'), trim($location));
				$pjJobModel->where("(t1.address_city LIKE '%$location%' OR t1.address_state LIKE '%$location%' OR t12.content LIKE '%$location%' OR t11.content LIKE '%$location%')");
				$has_filter = true;
			}
		}
		$total = $pjJobModel->findCount()->getData();
		
		$rowCount = $this->option_arr['o_item_per_page'];
		$pages = ceil($total / $rowCount);
		$page = isset($_GET['pjPage']) && (int) $_GET['pjPage'] > 0 ? intval($_GET['pjPage']) : 1;
		$offset = ((int) $page - 1) * $rowCount;
		if ($page > $pages)
		{
			$page = $pages;
		}
		$orderby = 't1.is_featured DESC, t1.created DESC';
		if(isset($_GET['sort_by']))
		{
			switch ($_GET['sort_by'])
			{
				case 'date':
					$orderby = 't1.created DESC';
					break;
				case 'type':
					$orderby = 't3.content ASC, t1.created DESC';
					break;
				case 'category':
					$orderby = 't5.content ASC, t1.created DESC';
					break;
			}
		}
		
		$arr = $pjJobModel
			->orderBy($orderby)
			->limit($rowCount, $offset)
			->findAll()
			->getData();
		
		$type_arr = pjTypeModel::factory()
			->select("t1.*, t2.content AS name,
					  (SELECT COUNT(TJ.id) FROM `".$pjJobModel->getTable()."` AS TJ WHERE TJ.type_id=t1.id AND (TJ.status = 'T' OR (TJ.status = 'E' AND TJ.expired >= CURDATE())) AND TJ.employer_id IN (SELECT `TE`.id FROM `".$employer_table."` AS `TE` WHERE `TE`.status='T' ) ) AS cnt_jobs")
		  ->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();
		
		$category_arr = pjCategoryModel::factory()
			->select("t1.*, t2.content AS name, (SELECT COUNT(*) FROM `".$pjJobModel->getTable()."` AS TJ WHERE TJ.category_id=t1.id AND (TJ.status = 'T' OR (TJ.status = 'E' AND TJ.expired >= CURDATE())) AND TJ.employer_id IN (SELECT `TE`.id FROM `".$employer_table."` AS `TE` WHERE `TE`.status='T' ) ) AS cnt_jobs")
			->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();
		
		$filter_arr = array();
		$_arr = pjFilterModel::factory()
			->select("t1.*, t2.content AS name, (SELECT COUNT(TJF.job_id) FROM `".pjJobFilterModel::factory()->getTable()."` AS TJF WHERE TJF.filter_id=t1.id AND TJF.job_id IN (SELECT TJ.id FROM `".$pjJobModel->getTable()."` AS TJ WHERE (TJ.status = 'T' OR (TJ.status = 'E' AND TJ.expired >= CURDATE())) AND TJ.employer_id IN (SELECT `TE`.id FROM `".$employer_table."` AS `TE` WHERE `TE`.status='T'))) AS cnt_jobs")
			->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('arr', $arr);
		$this->set('type_arr', $type_arr);
		$this->set('category_arr', $category_arr);
		$this->set('filter_arr', $filter_arr);
		$this->set('has_filter', $has_filter);
		$this->set('paginator', array('pages' => $pages, 'total' => $total));
	}
	
	public function pjActionFeatured()
	{
		$this->set('arr', $this->getFeaturedJobs($this->option_arr, $this->getLocaleId()));
	}
	
	public function pjActionSearch()
	{
		$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();
		
		$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();
		
		$filter_arr = array();
		$_arr = pjFilterModel::factory()
			->select("t1.*, t2.content AS name, (SELECT COUNT(TJF.job_id) FROM `".pjJobFilterModel::factory()->getTable()."` AS TJF WHERE TJF.filter_id=t1.id AND TJF.job_id IN (SELECT TJ.id FROM `".pjJobModel::factory()->getTable()."` AS TJ WHERE TJ.status = 'T' OR (TJ.status = 'E' AND TJ.expired >= CURDATE())) ) AS cnt_jobs")
			->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('category_arr', $category_arr);
		$this->set('country_arr', $country_arr);
		$this->set('type_arr', $type_arr);
		$this->set('filter_arr', $filter_arr);
	}
	
	public function pjActionLogin()
	{
		if(isset($_POST['employer_login']))
		{
			$path = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
			$path = $path == '/' ? '' : $path;
			if (!isset($_POST['email']) || !isset($_POST['password']) ||
				!pjValidation::pjActionNotEmpty($_POST['email']) ||
				!pjValidation::pjActionNotEmpty($_POST['password']) ||
				!pjValidation::pjActionEmail($_POST['email']))
			{
				if ($this->option_arr['o_seo_url'] == 'No')
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionLogin&tab=employer&err=3");
				}else{
					pjUtil::redirect($path . "/job-login.html?&tab=employer&err=3");
				}
			}
			$pjEmployerModel = pjEmployerModel::factory();
			$employer = $pjEmployerModel
				->where('t1.email', $_POST['email'])
				->where(sprintf("t1.password = AES_ENCRYPT('%s', '%s')", $pjEmployerModel->escapeStr($_POST['password']), PJ_SALT))
				->limit(1)
				->findAll()
				->getData();
			if (count($employer) != 1)
			{
				if ($this->option_arr['o_seo_url'] == 'No')
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionLogin&tab=employer&err=0");
				}else{
					pjUtil::redirect($path . "/job-login.html?&tab=employer&err=0");
				}
			} else {
				$employer = $employer[0];
				$employer['is_employer'] = true;
				unset($employer['password']);
				
				if ($employer['status'] != 'T')
				{
					if ($this->option_arr['o_seo_url'] == 'No')
					{
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionLogin&tab=employer&err=1");
					}else{
						pjUtil::redirect($path . "/job-login.html?&tab=employer&err=1");
					}
				}
				
				$last_login = date("Y-m-d H:i:s");
    			$_SESSION[$this->defaultUser] = $employer;
    			
    			$data = array();
    			$data['last_login'] = $last_login;
    			$data['ip_last_login'] = $_SERVER['REMOTE_ADDR'];
    			$pjEmployerModel->reset()->setAttributes(array('id' => $employer['id']))->modify($data);

    			if ($this->isEmployer())
    			{
	    			pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdmin&action=pjActionIndex");
    			}
			}
		}else if(isset($_POST['candidate_login'])){
			$path = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
			$path = $path == '/' ? '' : $path;
			if (!isset($_POST['email']) || !isset($_POST['password']) ||
				!pjValidation::pjActionNotEmpty($_POST['email']) ||
				!pjValidation::pjActionNotEmpty($_POST['password']) ||
				!pjValidation::pjActionEmail($_POST['email']))
			{
				if ($this->option_arr['o_seo_url'] == 'No')
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionLogin&tab=candidate&err=3");
				}else{
					pjUtil::redirect($path . "/job-login.html?&tab=candidate&err=3");
				}
			}
			$pjEmployeeModel = pjEmployeeModel::factory();
			$employee = $pjEmployeeModel
				->where('t1.email', $_POST['email'])
				->where(sprintf("t1.password = AES_ENCRYPT('%s', '%s')", $pjEmployeeModel->escapeStr($_POST['password']), PJ_SALT))
				->limit(1)
				->findAll()
				->getData();
			if (count($employee) != 1)
			{
				if ($this->option_arr['o_seo_url'] == 'No')
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionLogin&tab=candidate&err=0");
				}else{
					pjUtil::redirect($path . "/job-login.html?&tab=candidate&err=0");
				}
			} else {
				$employee = $employee[0];
				$employee['is_employee'] = true;
				unset($employee['password']);
				
				if ($employee['status'] != 'T')
				{
					if ($this->option_arr['o_seo_url'] == 'No')
					{
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionLogin&tab=candidate&err=1");
					}else{
						pjUtil::redirect($path . "/job-login.html?&tab=candidate&err=1");
					}
				}
				
				$last_login = date("Y-m-d H:i:s");
    			$_SESSION[$this->defaultCandidate] = $employee;
    						
    			$data = array();
    			$data['last_login'] = $last_login;
    			$pjEmployeeModel->reset()->setAttributes(array('id' => $employee['id']))->modify($data);

    			if ($this->option_arr['o_seo_url'] == 'No')
    			{
    				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionIndex");
    			}else{
    				if(empty($this->option_arr['o_job_page']))
    				{
    					pjUtil::redirect($path . "/job-home.html");
    				}else{
    					pjUtil::redirect($this->option_arr['o_job_page']);
    				}
    			}
			}
		}else{
			$this->set('social_urls', $this->getScocialUrls());
		}
	}
	
	public function pjActionLogout()
	{
		if ($this->checkLogin())
        {
        	unset($_SESSION[$this->defaultCandidate]);
        }
        if ($this->option_arr['o_seo_url'] == 'No')
        {
       		pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionJobs" . (isset($_POST['iframe']) ? '&iframe' : NULL));
        }else{
        	if(empty($this->option_arr['o_job_page']))
        	{
	        	$path = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
	        	$path = $path == '/' ? '' : $path;
	        	pjUtil::redirect($path . "/job-home.html");
        	}else{
        		pjUtil::redirect($this->option_arr['o_job_page']);
        	}
        }
	}
	
	public function pjActionView()
	{
		$id = $_GET['id'];
		
		$pjJobModel = pjJobModel::factory();
		$pjFileModel = pjFileModel::factory();
		$arr = $pjJobModel
			->select('t1.*, t7.content AS job_title, t8.content AS job_description, t3.content AS type_title, t2.status AS type_status,
							t5.content AS category, t4.status AS category_status,t6.content AS country,
							t9.logo, t9.thumb, t9.company_name, t9.contact_name, t9.url, t9.phone, t9.email AS emp_email, t10.content as about_company,
							t11.content as meta_title, t12.content as meta_keywords, t13.content as meta_description,
							t14.content AS lang_address, t15.content AS lang_city, t16.content AS lang_state')
			->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", 'left')
			->join('pjMultiLang', "t10.model='pjEmployer' AND t10.foreign_id=t1.employer_id AND t10.field='description' AND t10.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t11.model='pjJob' AND t11.foreign_id=t1.id AND t11.field='meta_title' AND t11.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t12.model='pjJob' AND t12.foreign_id=t1.id AND t12.field='meta_keywords' AND t12.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t13.model='pjJob' AND t13.foreign_id=t1.id AND t13.field='meta_description' AND t13.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t14.model='pjJob' AND t14.foreign_id=t1.id AND t14.field='address_content' AND t14.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t15.model='pjJob' AND t15.foreign_id=t1.id AND t15.field='address_city' AND t15.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t16.model='pjJob' AND t16.foreign_id=t1.id AND t16.field='address_state' AND t16.locale='".$this->getLocaleId()."'", 'left')
			->find($id)
			->getData();

		if(empty($arr['type_title']) || $arr['type_status'] == 'F')
		{
			$this->set('status', 5);
		}		
		if(empty($arr['category']) || $arr['category_status'] == 'F')
		{
			$this->set('status', 6);
		}		
		if($arr['status'] == 'F')
		{
			$this->set('status', 3);
		}else if($arr['status'] == 'E'){
			if($arr['expired'] < date('Y-m-d'))
			{
				$this->set('status', 4);
			}
		}
		if(!empty($arr['employer_id']))
		{
			$employer_id = $arr['employer_id'];
			$employer_arr = pjEmployerModel::factory()->find($employer_id)->getData();
			if(!empty($employer_arr))
			{
				if($employer_arr['status'] == 'F')
				{
					$this->set('status', 2);
				}
			}else{
				$this->set('status', 1);
			}
		}
			
		if ($this->checkLogin())
        {
        	$candidate = $_SESSION[$this->defaultCandidate];
        	$cv_arr = array();
        	$file_arr = $pjFileModel->select('t1.*')->where('foreign_id', $candidate['id'])->where('file_type', 'employee')->findAll()->getData();
        	if(!empty($file_arr))
        	{
        		$cv_arr = $file_arr[0];
        		$this->set('cv_arr', $cv_arr);
        	}
        	
        	$is_applied = false;
        	$cnt_apps = pjApplicationModel::factory()->where('t1.job_id', $id)->where("(t1.employee_id='".$candidate['id']."' OR t1.email='".$candidate['email']."')")->findCount()->getData();
        	if($cnt_apps > 0)
        	{
        		$is_applied = true;
        	}
        	$this->set('is_applied', $is_applied);
        }
        		
		$views = intval($arr['views']) + 1;
        $pjJobModel->reset()->where('id', $id)->limit(1)->modifyAll(array('views' => $views));
        
        $filter_arr = array();
        $_arr = pjFilterModel::factory()
	        ->select("t1.*, t2.content AS name, (SELECT COUNT(TJF.job_id) FROM `".pjJobFilterModel::factory()->getTable()."` AS TJF WHERE TJF.filter_id=t1.id AND TJF.job_id = '".$id."') AS cnt_jobs")
	        ->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;
        }
        
        $og_image = '';
        if(!empty($arr['logo']))
        {
        	$og_image = PJ_INSTALL_URL . $arr['logo'];
        }
        $meta_title = pjSanitize::html($arr['job_title']);
        $meta_description = pjUtil::truncateDescription(pjUtil::html2txt(html_entity_decode($arr['job_description'])), 160, ' ');
        if(!empty($arr['meta_title']))
        {
        	$meta_title = pjSanitize::html($arr['meta_title']);
        }
        if(!empty($arr['meta_description']))
        {
        	$meta_description = pjSanitize::html($arr['meta_description']);
        }
        $meta_keywords = '';
        if(!empty($arr['meta_keywords']))
        {
        	$meta_keywords = pjSanitize::html($arr['meta_keywords']);
        }
        $this->set('meta_arr', array(
        		'title' => $meta_title,
        		'keywords' => $meta_keywords,
        		'description' => $meta_description,
        		'url' => pjUtil::getPageURL(),
        		'og_title' => $meta_title,
        		'og_image' => $og_image,
        		'body' => $meta_description
        ));
        
        if(isset($_SESSION[$this->defaultError]))
        {
        	$this->set('err', $_SESSION[$this->defaultError]);
        	unset($_SESSION[$this->defaultError]);
        }
        
		$this->set('arr', $arr);
		$this->set('filter_arr', $filter_arr);
		$this->set('filter_id_arr', pjJobFilterModel::factory()->where('job_id', $id)->findAll()->getDataPair(null, 'filter_id'));
	}
	
	public function pjActionApply()
	{
		$pjApplicationModel = pjApplicationModel::factory();
		
		$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($_POST['job_id'])
			->getData();
		
		if ($this->option_arr['o_seo_url'] == 'No')
		{
			$url = $_SERVER['SCRIPT_NAME'] . "?controller=".$_GET['controller']."&action=pjActionView&id=" . $arr['id'] .(isset($_GET['iframe']) ? '&iframe' : NULL);
		} else {
			$path = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
			$path = $path == '/' ? '' : $path;
			$url = $path .'/'. $this->friendlyURL($arr['job_title']) . "-". $arr['id'] . ".html";
		}
		
		$err = '0';
		if(!isset($_POST['captcha']) || empty($_POST['captcha']))
		{
			$err = '3';
		}else if(!pjCaptcha::validate($_POST['captcha'], $_SESSION[$this->defaultCaptcha])){
			$err = '4';
		}
		if($err != '0')
		{
			$_SESSION[$this->defaultError] = $err;
			pjUtil::redirect($url);
		}
		unset($_SESSION[$this->defaultCaptcha]);

		$data = array();
		if(!isset($_POST['employee_id']))
		{
			if (!isset($_POST['email']) || !isset($_POST['fname']) || !isset($_POST['lname']) ||
				!pjValidation::pjActionNotEmpty($_POST['email']) ||
				!pjValidation::pjActionNotEmpty($_POST['fname']) ||
				!pjValidation::pjActionEmail($_POST['email']) ||
				!pjValidation::pjActionNotEmpty($_POST['lname']))
			{
				$_SESSION[$this->defaultError] = 'data_inv';
				pjUtil::redirect($url);
			}
		}else{
			$employee = $_SESSION[$this->defaultCandidate];
			$data['email'] = $employee['email'];
			$data['fname'] = $employee['fname'];
			$data['lname'] = $employee['lname'];
		}
		$data['status'] = 'N';
		$id = $pjApplicationModel->setAttributes(array_merge($_POST, $data))->insert()->getInsertId();
		if ($id !== false && (int) $id > 0)
		{
			$err = '1';
			if((isset($_POST['cv_option']) && $_POST['cv_option'] == 'new') || !isset($_POST['cv_option']))
			{
				if (isset($_FILES['cv']) && !empty($_FILES['cv']['tmp_name']))
				{
					$file = $_FILES['cv'];
					
					$pjFileModel = pjFileModel::factory();
					$data = array();
					$data['foreign_id'] = $id;
					$handle = new pjUpload();
					$handle->setAllowedExt(array('doc', 'docx', 'pdf'));
					if ($handle->load($file)) {
						$hash = md5(uniqid(rand(), true));
						$file_ext = $handle->getExtension();
						$file_path = PJ_UPLOAD_PATH . 'files/applications/' . $id . "_" . $hash . '.' . $file_ext;
						if($handle->save(PJ_INSTALL_PATH . $file_path))
						{
							$data['file_path'] = $file_path;
							$data['file_name'] = $file['name'];
							$data['mime_type'] = $file['type'];
							$data['hash'] = $hash;
							$data['file_type'] = 'application';
							
							$pjFileModel->setAttributes($data)->insert();
						}else{
							$err = '2';
						}
					}else{
						$err = '2';
					}
				}
			}
			if (isset($_POST['i18n']))
			{
				pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjApplication');
			}
			
			$app_arr = $pjApplicationModel	->reset()->select('t1.*, t2.job_refid')
											->join('pjJob', 't2.id = t1.job_id', 'left')
											->find($id)->getData();
			$app_arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($app_arr['id'], 'pjApplication');
			
			$arr = array();
			$pjNotificationModel = pjNotificationModel::factory();
			$notify_arr = $pjNotificationModel->findAll()->getData();
			foreach($notify_arr as $v)
			{
				$v['i18n'] = pjMultiLangModel::factory()->getMultiLang($v['id'], 'pjNotification');
				$arr[] = $v;
			}
			
			$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'])
						;
			}
			
			$from = $this->getFromEmail($this->option_arr);
			
			$pjEmail->setContentType('text/html');
			$pjEmail->setFrom($from);
			
			foreach($arr as $v)
			{
				if($v['id'] != 1 && $v['id'] != 2)
				{
					continue;
				}
				$subject = $v['i18n'][$this->getLocaleId()]['subject'.$v['id']];
				$message = $v['i18n'][$this->getLocaleId()]['message'.$v['id']];
				$pjEmail->setSubject($subject);
				if($v['id'] == 1)
				{
					$message = str_replace(array('{fname}', '{refid}'), array($app_arr['fname'], $app_arr['job_refid']), $message);
					$to = $app_arr['email'];
					
					$pjEmail->setTo($to);
					$pjEmail->send($message);
				}
				if($v['id'] == 2)
				{
					$message = str_replace(array('{refid}', '{fname}', '{lname}', '{email}', '{notes}'), array($app_arr['job_refid'], $app_arr['fname'], $app_arr['lname'], $app_arr['email'], $app_arr['i18n'][$this->getLocaleId()]['notes'] ), $message);
					
					$job_arr = pjJobModel::factory()->select('t1.*, t2.email')
													->join('pjEmployer', 't2.id = t1.employer_id')
													->find($app_arr['job_id'])->getData();
					$to = $job_arr['email'];
					$pjEmail->setTo($to);
					$pjEmail->send($message);
				}
			}
		} else {
			$err = '0';
		}
		$_SESSION[$this->defaultError] = $err;
		pjUtil::redirect($url);
	}
	
	public function pjActionRegister()
	{
		if(isset($_POST['employer_register']))
		{
			$path = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
			$path = $path == '/' ? '' : $path;
			
			$err = NULL;
			if(!isset($_POST['captcha']) || empty($_POST['captcha']))
			{
				$err = '5';
			}else if(!pjCaptcha::validate($_POST['captcha'], $_SESSION[$this->defaultCaptcha . 'Employer'])){
				$err = '6';
			}
			if($err != NULL)
			{
				if ($this->option_arr['o_seo_url'] == 'No')
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionRegister&tab=employer&err=" . $err);
				}else{
					pjUtil::redirect($path . '/job-register.html?tab=employer&err=' . $err);
				}
			}
			unset($_SESSION[$this->defaultCaptcha . 'Employer']);
			
			$pjEmployerModel = pjEmployerModel::factory();
			
			if (!isset($_POST['email']) || !isset($_POST['password']) || !isset($_POST['company_name']) ||
				!pjValidation::pjActionNotEmpty($_POST['email']) ||
				!pjValidation::pjActionNotEmpty($_POST['password']) ||
				!pjValidation::pjActionEmail($_POST['email']) ||
				!pjValidation::pjActionNotEmpty($_POST['company_name']))
			{
				if ($this->option_arr['o_seo_url'] == 'No')
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionRegister&tab=employer&err=data_inv");
				}else{
					pjUtil::redirect($path . '/job-register.html?tab=employer&err=data_inv');
				}
			}
			
			$data = array();
			$err = '1';
			if($this->option_arr['o_employer_confirmed'] == 'auto'){
				$data['status'] = 'T';
				$err = '1';
			}else if($this->option_arr['o_employer_confirmed'] == 'no'){
				$data['status'] = 'F';
				$err = '2';
			}else if($this->option_arr['o_employer_confirmed'] == 'manual'){
				$data['status'] = 'F';
				$err = '4';
			}
			$data['ip_registered'] = pjUtil::getClientIp();
			$id = $pjEmployerModel->setAttributes(array_merge($_POST, $data))->insert()->getInsertId();
			if ($id !== false && (int) $id > 0)
			{
				if (isset($_FILES['logo']) && !empty($_FILES['logo']['tmp_name']))
				{
					if(getimagesize($_FILES['logo']["tmp_name"]) != false)
					{
						$Image = new pjImage();
						if ($Image->getErrorCode() !== 200)
						{
							$Image->setAllowedTypes(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg'));
							if ($Image->load($_FILES['logo']))
							{
								$resp = $Image->isConvertPossible();
								if ($resp['status'] === true)
								{
									$hash = md5(uniqid(rand(), true));
									
									$Image->loadImage();
									
									$Image->resizeSmart(73, 73);
									$thumb_path = PJ_UPLOAD_PATH . 'logos/thumbs/' . $id . '_' . $hash . '.' . $Image->getExtension();
									$Image->saveImage(PJ_INSTALL_PATH . $thumb_path);
									$logo_path = PJ_UPLOAD_PATH . 'logos/' . $id . '_' . $hash . '.' . $Image->getExtension();
									$Image->saveImage(PJ_INSTALL_PATH . $logo_path);
									$d = array();
									$d['thumb'] = $thumb_path;
									$d['logo'] = $logo_path;
										
									$pjEmployerModel->reset()->where('id', $id)->limit(1)->modifyAll($d);
								}
							}
						}
					}else{
						$err = '3';
					}
				}
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjEmployer');
				}
				if($this->option_arr['o_employer_confirmed'] == 'manual')
				{
					pjAppController::pjActionEmployerConfirmSend($this->option_arr, $id, $this->getLocaleId());
				}
				
			} else {
				$err = '0';
			}
			if ($this->option_arr['o_seo_url'] == 'No')
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionRegister&tab=employer&err=$err");
			}else{
				pjUtil::redirect($path . '/job-register.html?tab=employer&err=' . $err);
			}
		}elseif(isset($_POST['candidate_register'])){
			$path = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
			$path = $path == '/' ? '' : $path;
			
			$err = NULL;
			if(!isset($_POST['captcha']) || empty($_POST['captcha']))
			{
				$err = '5';
			}else if(!pjCaptcha::validate($_POST['captcha'], $_SESSION[$this->defaultCaptcha . 'Candidate'])){
				$err = '6';
			}
			if($err != NULL)
			{
				if ($this->option_arr['o_seo_url'] == 'No')
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionRegister&tab=candidate&err=" . $err);
				}else{
					pjUtil::redirect($path . '/job-register.html?tab=candidate&err=' . $err);
				}
			}
			unset($_SESSION[$this->defaultCaptcha . 'Candidate']);
			
			$pjEmployerModel = pjEmployerModel::factory();
			
			if (!isset($_POST['email']) || !isset($_POST['password']) || !isset($_POST['fname']) || !isset($_POST['lname']) ||
				!pjValidation::pjActionNotEmpty($_POST['email']) ||
				!pjValidation::pjActionNotEmpty($_POST['password']) ||
				!pjValidation::pjActionEmail($_POST['email']) ||
				!pjValidation::pjActionNotEmpty($_POST['fname'])||
				!pjValidation::pjActionNotEmpty($_POST['lname']))
			{
				if ($this->option_arr['o_seo_url'] == 'No')
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionRegister&tab=candidate&err=data_inv");
				}else{
					pjUtil::redirect($path . '/job-register.html?tab=candidate&err=data_inv');
				}
			}
			
			$data = array();
			$err = '1';
			if($this->option_arr['o_employee_confirmed'] == 'auto')
			{
				$data['status'] = 'T';
				$err = '1';
			}else if($this->option_arr['o_employee_confirmed'] == 'no'){
				$data['status'] = 'F';
				$err = '2';
			}else if($this->option_arr['o_employee_confirmed'] == 'manual'){
				$data['status'] = 'F';
				$err = '3';
			}
			$id = pjEmployeeModel::factory(array_merge($_POST, $data))->insert()->getInsertId();
			if ($id !== false && (int) $id > 0)
			{
				if (isset($_FILES['cv']) && !empty($_FILES['cv']['tmp_name']))
				{
					$file = $_FILES['cv'];
					
					$pjFileModel = pjFileModel::factory();
					$data = array();
					$data['foreign_id'] = $id;
					$handle = new pjUpload();
					$handle->setAllowedExt(array('doc', 'docx', 'pdf'));
					if ($handle->load($file)) {
						$hash = md5(uniqid(rand(), true));
						$file_ext = $handle->getExtension();
						$file_path = PJ_UPLOAD_PATH . 'files/employees/' . $id . "_" . $hash . '.' . $file_ext;
						if($handle->save(PJ_INSTALL_PATH . $file_path))
						{
							$data['file_path'] = $file_path;
							$data['file_name'] = $file['name'];
							$data['mime_type'] = $file['type'];
							$data['hash'] = $hash;
							$data['file_type'] = 'employee';
							
							$pjFileModel->setAttributes($data)->insert();
						}
					}else{
						$err = '4';
					}
				}
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjEmployee');
				}
				if($this->option_arr['o_employee_confirmed'] == 'manual')
				{
					pjAppController::pjActionEmployeeConfirmSend($this->option_arr, $id, $this->getLocaleId());
				}
			} else {
				$err = '0';
			}
			if ($this->option_arr['o_seo_url'] == 'No')
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionRegister&tab=candidate&err=$err");
			}else{
				pjUtil::redirect($path . '/job-register.html?tab=candidate&err=' . $err);
			}
		}else{
			
			$this->set('social_urls', $this->getScocialUrls());
		}
	}
	
	public function pjActionProfile()
	{
		if($this->checkLogin())
		{
			$current_candidate = $_SESSION[$this->defaultCandidate];
			
			$path = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
			$path = $path == '/' ? '' : $path;
			
			if(isset($_POST['profile_update']))
			{
				if (!isset($_POST['email']) || !isset($_POST['password']) || !isset($_POST['cpassword']) || !isset($_POST['fname']) || !isset($_POST['lname']) ||
						!pjValidation::pjActionNotEmpty($_POST['email']) ||
						!pjValidation::pjActionNotEmpty($_POST['password']) ||
						!pjValidation::pjActionNotEmpty($_POST['cpassword']) ||
						!pjValidation::pjActionEmail($_POST['email']) ||
						!pjValidation::pjActionNotEmpty($_POST['fname'])||
						!pjValidation::pjActionNotEmpty($_POST['lname']))
				{
					if ($this->option_arr['o_seo_url'] == 'No')
					{
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionProfile&err=data_inv");
					}else{
						pjUtil::redirect($path . '/job-profile.html?err=data_inv');
					}
				}
				
				$pjEmployeeModel = pjEmployeeModel::factory();
				
				if($_POST['password'] == 'password' || $_POST['password'] == ''){
					unset($_POST['password']);
				}
				$pjEmployeeModel->where('id', $_POST['id'])->limit(1)->modifyAll($_POST);
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjEmployee');
				}
				
				if (isset($_FILES['cv']) && !empty($_FILES['cv']['tmp_name']))
				{
					
					$pjFileModel = pjFileModel::factory();
					$file_arr = $pjFileModel->where("`file_type`", 'employee')->where("`foreign_id`", $_POST['id'])->findAll()->getData();
					
					$file = $_FILES['cv'];
					$data = array();
					$data['foreign_id'] = $_POST['id'];
					$handle = new pjUpload();
					$handle->setAllowedExt(array('doc', 'docx', 'pdf'));
					if ($handle->load($file)) {
						$hash = md5(uniqid(rand(), true));
						$file_ext = $handle->getExtension();
						
						$file_path = PJ_UPLOAD_PATH . 'files/employees/' . $_POST['id'] . "_" . $hash . '.' . $file_ext;
						if($handle->save(PJ_INSTALL_PATH . $file_path))
						{
							$data['file_path'] = $file_path;
							$data['file_name'] = $file['name'];
							$data['mime_type'] = $file['type'];
							$data['hash'] = $hash;
							$data['file_type'] = 'employee';
							
							if(!empty($file_arr)){
								if (!empty($file_arr[0]['file_path']) && is_file(PJ_INSTALL_PATH . $file_arr[0]['file_path']))
								{
									@unlink(PJ_INSTALL_PATH . $file_arr[0]['file_path']);
								}
								$pjFileModel->reset()->where('id', $file_arr[0]['id'])->limit(1)->modifyAll($data);
							}else{
								$pjFileModel->setAttributes($data)->insert();
							}
						}else{
							if ($this->option_arr['o_seo_url'] == 'No')
							{
								pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionProfile&err=2");
							}else{
								pjUtil::redirect($path . '/job-profile.html?err=2');
							}
						}
					}else{
						if ($this->option_arr['o_seo_url'] == 'No')
						{
							pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionProfile&err=2");
						}else{
							pjUtil::redirect($path . '/job-profile.html?err=2');
						}
					}
				}
				
				$employee = $pjEmployeeModel->reset()->find($_POST['id'])->getData();
				$_SESSION[$this->defaultCandidate] = $employee;
				
				if ($this->option_arr['o_seo_url'] == 'No')
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionProfile&err=1" . (isset($_POST['iframe']) ? '&iframe' : NULL));
				}else{
					pjUtil::redirect($path . '/job-profile.html?err=1');
				}
			}else{
				$arr = pjEmployeeModel::factory()->find($current_candidate['id'])->getData();
				$file_arr = pjFileModel::factory()->where("`file_type`", 'employee')->where("`foreign_id`", $current_candidate['id'])->findAll()->getData();
				
				if(!empty($file_arr)){
					$this->set('file_arr', $file_arr[0]);
				}
				$this->set('arr', $arr);
				
			}
		}else{
			if ($this->option_arr['o_seo_url'] == 'No')
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionLogin" . (isset($_POST['iframe']) ? '&iframe' : NULL));
			}else{
				pjUtil::redirect($path . '/job-login.html');
			}
		}
	}
	
	public function pjActionForgotPassword()
	{
		if(isset($_POST['forgot_password']))
		{
			$err = 1;
			$email = stripslashes($_POST['email']);
			
			$is_employer = false;
			$is_employee = false;
			$fname = '';
			$password = '';
			
			$pjEmployerModel = pjEmployerModel::factory()->where('t1.email', $email);
			$employer_arr = $pjEmployerModel->findAll()->getData();
			if(count($employer_arr) > 0)
			{
				$is_employer = true;
				$arr = $employer_arr[0];
				$fname = $arr['contact_name'];
				$password = $arr['password'];
			}
			if($is_employer == false)
			{
				$pjEmployeeModel = pjEmployeeModel::factory()->where('t1.email', $email);
				$employee_arr = $pjEmployeeModel->findAll()->getData();
				if(count($employee_arr) > 0)
				{
					$is_employee = true;
					$arr = $employee_arr[0];
					$fname = $arr['fname'];
					$password = $arr['password'];
				}
			}
			
			if($is_employer == false && $is_employee == false)
			{
				$err = 0;
			}else{
				$notify_arr = pjNotificationModel::factory()->find(4)->getData();
				$notify_arr['i18n'] = pjMultiLangModel::factory()->getMultiLang(4, 'pjNotification');
				
				$subject = $notify_arr['i18n'][$this->getLocaleId()]['subject4'];
				$message = $notify_arr['i18n'][$this->getLocaleId()]['message4'];
				$message = str_replace(array('{fname}', '{password}'), array($fname, $password), $message);
				
				$to = $email;
				$from = $this->getFromEmail($this->option_arr);
				
				$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->setTo($to);
				$pjEmail->setSubject($subject);
				$pjEmail->send($message);
			}
			
			if ($this->option_arr['o_seo_url'] == 'No')
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionForgotPassword&err=$err");
			}else{
				$path = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
				$path = $path == '/' ? '' : $path;
				pjUtil::redirect($path . '/job-forgot-password.html?err=' . $err);
			}
		}else{
			
		}
	}
	
	public function pjActionDeleteCV()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$file_id = $_GET['id'];
			$hash = $_GET['hash'];
			
			$pjFileModel = pjFileModel::factory();
			
			$arr = $pjFileModel->find($file_id)->getData();
			if(!empty($arr))
			{
				if($hash == $arr['hash'])
				{
					if ($pjFileModel->reset()->setAttributes(array('id' => $file_id))->erase()->getAffectedRows() == 1){
						if (!empty($arr['file_path']) && is_file(PJ_INSTALL_PATH . $arr['file_path']))
						{
							@unlink(PJ_INSTALL_PATH . $arr['file_path']);
						}
						echo '100';
					}else{
						echo '103';
					}
				}else{
					echo '102';
				}
			}else{
				echo '101';
			}
		}
		exit;
	}
	
	public function pjActionDownloadFile()
	{
		$id = $_GET['id'];
		
		$arr = pjFileModel::factory()->find($id)->getData();
		if(!empty($arr))
		{
			if($_GET['hash'] == $arr['hash'])
			{
				pjToolkit::download(@file_get_contents(PJ_INSTALL_PATH . $arr['file_path']), $arr['file_name'], $arr['mime_type']);
			}
		}
		exit;
	}
	
	public function pjActionConfirmPayment()
	{
		$this->setAjax(true);
		
		if (pjObject::getPlugin('pjPaypal') === NULL)
		{
			$this->log('Paypal plugin not installed');
			pjAppController::jsonResponse(array('status' => 'ERR', 'text' => 'Paypal plugin not installed'));
		}
		
		$input = file_get_contents('php://input');
		$post = json_decode($input, true);
		if ($post) {
		    $_REQUEST = array_merge($_REQUEST, $post);
		}
		
		$pjPaymentModel = pjPaymentModel::factory();
		$pjJobModel = pjJobModel::factory();
		
		list($job_id, $period_id) = explode('-', $_REQUEST['custom']);
		
		$job_arr = $pjJobModel->find($job_id)->getData();
		$period_arr = pjPeriodModel::factory()->find($period_id)->getData();		
		$payment_arr = $pjPaymentModel->where('t1.job_id', $job_id)->orderBy('t1.date_to DESC')->limit(1)->findAll()->getData();
		$date_from = date("Y-m-d");
		if (count($payment_arr) === 1)
		{
			$date_from = $payment_arr[0]['date_to'];
		}
		
		$period = (int) $period_arr['days'];
		$price = (float) $period_arr['price'];
		
		list($year, $month, $day) = explode("-", $date_from);
		$date_to = date("Y-m-d", mktime(0, 0, 0, $month, $day + $period, $year));
		
		$params = array(
		    'request'		=> $_REQUEST,
		    'cancel_hash'	=> sha1($job_arr['id'].strtotime($job_arr['created']).PJ_SALT),
		    'txn_id' => @$payment_arr['txn_id'],
		    'paypal_address' => $this->option_arr['o_paypal_address'],
		    'deposit' => $price,
		    'currency' => $this->option_arr['o_currency'],
		    'key' => md5($this->option_arr['private_key'] . PJ_SALT)
		);
		$response = $this->requestAction(array('controller' => 'pjPaypal', 'action' => 'pjActionConfirm', 'params' => $params), array('return'));
		if ($response !== FALSE && isset($response['status']) && $response['status'] === 'OK')
		{
			$this->log('pjPaypal > pjActionConfirm > status == OK');
			$pjPaymentModel
				->reset()
				->setAttributes(array(
					'job_id' => $job_arr['id'],
					'date_from' => $date_from,
					'date_to' => $date_to,
					'txn_id' => $response['transaction_id'],
					'price' => $price
				))
				->insert();
			$current = time();
			if (!empty($job_arr['expired']) && $job_arr['expired'] != '0000-00-00')
			{
				$current = strtotime($job_arr['expired']);
			}
			pjJobModel::factory()
				->set('id', $job_arr['id'])
				->modify(array(
					'last_extend' => 'paid',
					'expired' => date("Y-m-d", $current + $period * 86400)
				));
			$this->log('Payment confirmed');
			pjAppController::jsonResponse(array('status' => 'OK', 'text' => 'Payment confirmed'));
		} elseif (!$response) {
			$this->log('Authorization failed');
			pjAppController::jsonResponse(array('status' => 'ERR', 'text' => 'Authorization failed'));
		} else {
			$this->log('Payment not confirmed');
			pjAppController::jsonResponse(array('status' => 'ERR', 'text' => 'Payment not confirmed'));
		}
	}
	
	public function pjActionConfirmStripe()
	{
		$this->setAjax(false);
		
		if (pjObject::getPlugin('pjStripe') === NULL)
		{
			$this->log('Stripe plugin not installed');
			pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminJobs&action=pjActionIndex");
		}
		
		if (!isset($_REQUEST['custom']) || !isset($_REQUEST['session_id']))
		{
			pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminJobs&action=pjActionIndex");
		}
		
		$pjPaymentModel = pjPaymentModel::factory();
		$pjJobModel = pjJobModel::factory();
		
		list($job_id, $period_id) = explode('-', $_REQUEST['custom']);
		
		$job_arr = $pjJobModel->find($job_id)->getData();
		$period_arr = pjPeriodModel::factory()->find($period_id)->getData();
		$payment_arr = $pjPaymentModel->where('t1.job_id', $job_id)->orderBy('t1.date_to DESC')->limit(1)->findAll()->getData();
		$date_from = date("Y-m-d");
		if (count($payment_arr) === 1)
		{
			$date_from = $payment_arr[0]['date_to'];
		}
		
		$period = (int) $period_arr['days'];
		$price = (float) $period_arr['price'];
		
		list($year, $month, $day) = explode("-", $date_from);
		$date_to = date("Y-m-d", mktime(0, 0, 0, $month, $day + $period, $year));
		
		$params = array(
		    'request'    => $_REQUEST,
		    'cancel_hash' => sha1($job_arr['id'].strtotime($job_arr['created']).PJ_SALT),
		    'deposit'    => $price,
		    'currency'   => $this->option_arr['o_currency'],
		    'foreign_id' => $job_arr['id'],
		    'key'        => md5($this->option_arr['private_key'] . PJ_SALT)
		);
		$response = $this->requestAction(array('controller' => 'pjStripe', 'action' => 'pjActionConfirm', 'params' => $params), array('return'));
		if ($response !== FALSE && isset($response['status']) && $response['status'] === 'OK')
		{
			$this->log('pjStripe > pjActionConfirm > status == OK');
			$pjPaymentModel
				->reset()
				->setAttributes(array(
					'job_id' => $job_arr['id'],
					'date_from' => $date_from,
					'date_to' => $date_to,
					'txn_id' => $response['transaction_id'],
					'price' => $price
				))
				->insert();
			$current = time();
			if (!empty($job_arr['expired']) && $job_arr['expired'] != '0000-00-00')
			{
				$current = strtotime($job_arr['expired']);
			}
			pjJobModel::factory()
				->set('id', $job_arr['id'])
				->modify(array(
					'last_extend' => 'paid',
					'expired' => date("Y-m-d", $current + $period * 86400)
				));
			$this->log('Payment confirmed');
			pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminJobs&action=pjActionIndex&extend=1");
		} else {
			$this->log('Payment not confirmed');
			pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminJobs&action=pjActionIndex");
		}
	}
	
	public function getFeaturedJobs($option_arr, $locale_id)
	{
		$pjJobModel = pjJobModel::factory();
		$pjJobModel->where('t1.is_featured', 'T');
		$pjJobModel->where("(t1.status = 'T' OR (t1.status = 'E' AND t1.expired >= CURDATE()))");
		$pjJobModel->where("t1.category_id IN (SELECT `TC`.`id` FROM `".pjCategoryModel::factory()->getTable()."` as `TC` WHERE `TC`.`status` ='T')");
		$pjJobModel->where("t1.type_id IN (SELECT `TT`.`id` FROM `".pjTypeModel::factory()->getTable()."` as `TT` WHERE `TT`.`status` ='T')");
		$pjJobModel->where("t1.employer_id IN (SELECT `TE`.`id` FROM `".pjEmployerModel::factory()->getTable()."` as `TE` WHERE `TE`.`status` ='T')");
		
		$sorting = 't1.created DESC';
		$cnt = $pjJobModel->findCount()->getData();
		if($cnt > $option_arr['o_featured_jobs'])
		{
			$sorting = 'RAND()';
		}
		$pjJobModel->limit($option_arr['o_featured_jobs'], 0);
		
		$arr = $pjJobModel
			->select('t1.*, t9.logo, t9.thumb, t9.company_name, t7.content AS job_title, 
					t8.content AS job_description, t3.content AS type_title, 
					t5.content AS category, t6.content AS country,
					t10.content AS lang_address, t11.content AS lang_city, t12.content AS lang_state')
			->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='".$locale_id."'", '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='".$locale_id."'", 'left')
			->join('pjMultiLang', "t6.model='pjCountry' AND t6.foreign_id=t1.country_id AND t6.field='name' AND t6.locale='".$locale_id."'", 'left')
			->join('pjMultiLang', "t7.model='pjJob' AND t7.foreign_id=t1.id AND t7.field='job_title' AND t7.locale='".$locale_id."'", 'left')
			->join('pjMultiLang', "t8.model='pjJob' AND t8.foreign_id=t1.id AND t8.field='job_description' AND t8.locale='".$locale_id."'", 'left')
			->join('pjEmployer', "t9.id=t1.employer_id AND t9.status='T'", 'left')
			->join('pjMultiLang', "t10.model='pjJob' AND t10.foreign_id=t1.id AND t10.field='address_content' AND t10.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t11.model='pjJob' AND t11.foreign_id=t1.id AND t11.field='address_city' AND t11.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t12.model='pjJob' AND t12.foreign_id=t1.id AND t12.field='address_state' AND t12.locale='".$this->getLocaleId()."'", 'left')
			->orderBy($sorting)
			->findAll()
			->getData();
		
		return $arr;
	}
	
	public function pjActionSocial()
	{
		$return_success = pjUtil::getParams('return_success');
		$return_failed = pjUtil::getParams('return_failed');
		$client_type = pjUtil::getParams('client_type');
		$network = pjUtil::getParams('network');
		
		if ($network == 'facebook')
		{
			pjUtil::redirect($this->getFacebookLoginUrl($return_success, $return_failed, $client_type));
		}else if ($network == 'linkedin'){
			pjUtil::redirect($this->getLinkedinLoginUrl($return_success, $return_failed, $client_type));
		}else{
			die('No supported!');
		}
		exit;
	}
	
	public function pjActionFacebook()
	{
		$state_session = isset($_SESSION['facebook_state']) ? $_SESSION['facebook_state'] : '';
	
		if (empty($state_session))
		{
			die();
		}
		
		$state = @unserialize($state_session);
				
		$return_success = $state['return_success'];
		$return_failed = $state['return_failed'];
		$client_type = $state['client'];
		
		$redirect_uri = PJ_INSTALL_URL . 'index.php?controller=pjLoad&action=pjActionFacebook';
		$user_profile = null;
		
		$facebook = new pjFacebook(
				$this->option_arr['o_facebook_api_key'],
				$this->option_arr['o_facebook_api_secret'],
				$redirect_uri
		);
		try {
			$facebook->requestAccessToken($_GET['code']);
			$facebook->requestValidateToken();
			$facebook->requestUser();
			$user_profile = $facebook->getUser();
		} catch (Exception $e) {
			echo $facebook->getAccessToken();
			echo '<pre style="clear:both;text-align:left" dir="ltr">';
			print_r($facebook->getError());
			echo '</pre>';
			echo $e->getMessage();
			exit;
		}
		
		if (empty($user_profile) || empty($user_profile->email))
		{
			pjUtil::redirect($return_failed);
		}else{
			$client = $this->getClientByEmail($user_profile->email, $client_type);
			$is_new = false;
			if (empty($client))
			{
				$user_name_arr = array();
				if(!empty($user_profile->firstName))
				{
					$user_name_arr[] = $user_profile->firstName;
				}
				if(!empty($user_profile->lastName))
				{
					$user_name_arr[] = $user_profile->lastName;
				}
				if ($client_type == 'employer')
				{
					$employer_status = 'F';
					if($this->option_arr['o_employer_confirmed'] == 'auto')
					{
						$employer_status = 'T';
					}
					$data = array(
							'email' => $user_profile->email,
							'password' => pjToolkit::getRandomPassword(),
							'contact_name' => !empty($user_profile->displayName) ? $user_profile->displayName : join(" ", $user_name_arr),
							'ip_registered'=> pjUtil::getClientIp(),
							'status' => $employer_status
					);
					$employer_id = pjEmployerModel::factory($data)->insert()->getInsertId();
					if ($employer_id !== false && (int) $employer_id > 0)
					{
						if($this->option_arr['o_employer_confirmed'] == 'manual')
						{
							pjAppController::pjActionEmployerConfirmSend($this->option_arr, $employer_id, $this->getLocaleId());
						}
					}
				}else{
					$employee_status = 'F';
					if($this->option_arr['o_employee_confirmed'] == 'auto')
					{
						$employee_status = 'T';
					}
					$data = array(
							'email' => $user_profile->email,
							'fname' => $user_profile->firstName,
							'lname' => $user_profile->lastName,
							'password' => pjToolkit::getRandomPassword(),
							'status' => $employee_status
					);
					$employee_id = pjEmployeeModel::factory($data)->insert()->getInsertId();
					if ($employee_id !== false && (int) $employee_id > 0)
					{
						if($this->option_arr['o_employee_confirmed'] == 'manual')
						{
							pjAppController::pjActionEmployeeConfirmSend($this->option_arr, $employee_id, $this->getLocaleId());
						}
					}
				}
				$client = $this->getClientByEmail($user_profile->email, $client_type);
				$is_new = true;
			}
			if (empty($client))
			{
				pjUtil::redirect($return_failed);
			}else{
				if ($client_type == 'employer')
				{
					if ($client['status'] != 'T')
					{
						pjUtil::redirect(PJ_INSTALL_URL . 'index.php?controller=pjAdmin&action=pjActionEmployerLogin&err=3');
					}else{
						if($is_new == true)
						{
							if($this->option_arr['o_employer_confirmed'] == 'auto')
							{
								$client['is_employer'] = true;
								$_SESSION[$this->defaultUser] = $client;
								pjUtil::redirect($return_success . '&' . http_build_query(array('facebook' => '1')));
							}else{
								pjUtil::redirect($return_failed);
							}
						}else{
							$client['is_employer'] = true;
							$_SESSION[$this->defaultUser] = $client;
							pjUtil::redirect($return_success . '&' . http_build_query(array('facebook' => '1')));
						}
					}
				}else{
					if ($client['status'] == 'T')
					{
						if($is_new == true)
						{
							if($this->option_arr['o_employee_confirmed'] == 'auto')
							{
								$_SESSION[$this->defaultCandidate] = $client;
								pjUtil::redirect($return_success);
							}else{
								pjUtil::redirect($return_failed);
							}
						}else{
							$_SESSION[$this->defaultCandidate] = $client;
							pjUtil::redirect($return_success);
						}
					}else{
						parse_str(parse_url($return_failed, PHP_URL_QUERY), $output);
						if(!empty($output))
						{
							if(isset($output['tab']) && $output['tab'] == 'candidate')
							{
								$return_failed .= '&err=1';
							}else{
								$return_failed .= '&tab=candidate&err=1';
							}
						}else{
							$return_failed .= '?tab=candidate&err=1';
						}
						pjUtil::redirect($return_failed);
					}
				}
			}
		}
		die();
	}
	
	public function pjActionLinkedin()
	{
		$error = pjUtil::getParams('error');
		$code = pjUtil::getParams('code');
		$state = pjUtil::getParams('state');
		$state_session = isset($_SESSION['linkedin_state'])? $_SESSION['linkedin_state']:'';

		if (empty($state_session) || $state_session != $state)
		{
			die();
		}else{
			$state = @unserialize($state_session);
			if ($state === false){
				die();
			}elseif (!empty($error)){ 
				$error_description = pjUtil::getParams('error_description');
				pjUtil::redirect($state['return_failed']);
			}else{
				$success_url = $state['return_success'];
				$redirect = PJ_INSTALL_URL . 'index.php?controller=pjLoad&action=pjActionLinkedin';
				$params = array(
					'grant_type' => 'authorization_code',
					'client_id' => $this->option_arr['o_linkedin_api_key'],
					'client_secret' => $this->option_arr['o_linkedin_api_secret'],
					'code' => $code,
					'redirect_uri' => $redirect,
				);
				$pjHttp = new pjHttp();
				$pjHttp->request('https://www.linkedin.com/oauth/v2/accessToken?' . http_build_query($params));

				$response = $pjHttp->getResponse();
				$json = self::jsonDecode($response);

				if (!empty($json->access_token)) {
					$emailData = $this->fetchLinkedin('/v2/emailAddress?q=members&projection=(elements*(handle~))', $json->access_token);
					$userData = $this->fetchLinkedin('/v2/me?projection=(id,firstName,lastName)', $json->access_token);

					if (!empty($userData) && !empty($emailData->elements[0]->{"handle~"}->emailAddress)) {
						$email = $emailData->elements[0]->{"handle~"}->emailAddress;

						$name_arr = array();
						if (!empty($userData->firstName)) {
							$preferredLocale = $userData->firstName->preferredLocale;
							$preferredLocaleKey = sprintf('%s_%s', $preferredLocale->language, $preferredLocale->country);
							$name_arr[] = $userData->firstName->localized->{$preferredLocaleKey};
						}
						if (!empty($userData->lastName)) {
							$preferredLocale = $userData->lastName->preferredLocale;
							$preferredLocaleKey = sprintf('%s_%s', $preferredLocale->language, $preferredLocale->country);
							$name_arr[] = $userData->lastName->localized->{$preferredLocaleKey};
						}

						$client = $this->getClientByEmail($email, $state['client']);
						$is_new = false;
						if (empty($client)) {
							if ($state['client'] == 'employer') {
								$employer_status = 'F';
								if ($this->option_arr['o_employer_confirmed'] == 'auto') {
									$employer_status = 'T';
								}

								$data = array(
									'email' => $email,
									'password' => pjToolkit::getRandomPassword(),
									'contact_name' => join(" ", $name_arr),
									'ip_registered' => pjUtil::getClientIp(),
									'status' => $employer_status
								);
								$employer_id = pjEmployerModel::factory($data)->insert()->getInsertId();
								if ($employer_id !== false && (int) $employer_id > 0) {
									if ($this->option_arr['o_employer_confirmed'] == 'manual') {
										pjAppController::pjActionEmployerConfirmSend($this->option_arr, $employer_id, $this->getLocaleId());
									}
								}
							}
							else {
								$employee_status = 'F';
								if ($this->option_arr['o_employee_confirmed'] == 'auto') {
									$employee_status = 'T';
								}

								$data = array(
									'email' => $email,
									'fname' => (!empty($name_arr[0])) ? $name_arr[0] : '',
									'lname' => (!empty($name_arr[1])) ? $name_arr[1] : '',
									'password' => pjToolkit::getRandomPassword(),
									'status' => $employee_status
								);
								$employee_id = pjEmployeeModel::factory($data)->insert()->getInsertId();
								if ($employee_id !== false && (int) $employee_id > 0) {
									if ($this->option_arr['o_employee_confirmed'] == 'manual') {
										pjAppController::pjActionEmployeeConfirmSend($this->option_arr, $employee_id, $this->getLocaleId());
									}
								}
							}
							$client = $this->getClientByEmail($email, $state['client']);
							$is_new = true;
						}

						if (empty($client)) {
							pjUtil::redirect($state['return_failed']);
						}
						else {
							if ($state['client'] == 'employer') {
								if ($client['status'] != 'T') {
									pjUtil::redirect(PJ_INSTALL_URL . 'index.php?controller=pjAdmin&action=pjActionEmployerLogin&err=3');
								}
								else {
									if ($is_new == true) {
										if ($this->option_arr['o_employer_confirmed'] == 'auto') {
											$client['is_employer']        = true;
											$_SESSION[$this->defaultUser] = $client;
											pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdmin&action=pjActionIndex" . '&' . http_build_query(array('linkedin' => '1')));
										}
										else {
											pjUtil::redirect($state['return_failed']);
										}
									}
									else {
										$client['is_employer']        = true;
										$_SESSION[$this->defaultUser] = $client;
										pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdmin&action=pjActionIndex" . '&' . http_build_query(array('linkedin' => '1')));
									}
								}
							}
							else {
								if ($client['status'] == 'T') {
									if ($is_new == true) {
										if ($this->option_arr['o_employee_confirmed'] == 'auto') {
											$_SESSION[$this->defaultCandidate] = $client;
											pjUtil::redirect($state['return_success']);
										}
										else {
											pjUtil::redirect($state['return_failed']);
										}
									}
									else {
										$_SESSION[$this->defaultCandidate] = $client;
										pjUtil::redirect($state['return_success']);
									}
								}
								else {
									parse_str(parse_url($state['return_failed'], PHP_URL_QUERY), $output);
									if (!empty($output)) {
										if (isset($output['tab']) && $output['tab'] == 'candidate') {
											$state['return_failed'] .= '&err=1';
										}
										else {
											$state['return_failed'] .= '&tab=candidate&err=1';
										}
									}
									else {
										$state['return_failed'] .= '?tab=candidate&err=1';
									}
									pjUtil::redirect($state['return_failed']);
								}
							}
						}
					}
					else {
						$this->log('LinkedIn login: Can not retrieve user data');
					}
				}
				else {
					$this->log('LinkedIn login: ' . $json->error_description);
				}
			}
		}
		die();
	}
	
	public function getClientByEmail($email, $type = 'candidate')
	{
		if($type == 'employer')
		{
			$pjEmployerModel = pjEmployerModel::factory()->where('t1.email', $email);
			$client = $pjEmployerModel->findAll()->getData();
		}else{
			$pjEmployeeModel = pjEmployeeModel::factory()->where('t1.email', $email);
			$client = $pjEmployeeModel->findAll()->getData();
		}
		if (empty($client))
		{
			return $client;
		}else{
			return $client[0];
		}
	}
	
	public function getScocialUrls()
	{
		$url_arr = array();
		$params = array();
		
		$current_url = pjUtil::getRequestUrl();
		
		if ($this->option_arr['o_seo_url'] == 'No')
		{
			$params['return_success'] = str_replace(strstr($current_url, "?controller"), "?controller=".$_GET['controller']."&action=pjActionIndex", $current_url);
		}else{
			$path = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
			$path = $path == '/' ? '' : $path;
			if(empty($this->option_arr['o_job_page']))
			{
				$params['return_success'] = $path . '/job-home.html';
			}else{
				$params['return_success'] = $this->option_arr['o_job_page'];
			}
		}
		$params['return_failed'] = str_replace(strstr($current_url, "?controller"), "?controller=".$_GET['controller']."&action=pjActionLogin", $current_url);
			
		$params['network'] = 'facebook';
		$params['client_type'] = 'candidate';
		$params['return_failed'] = str_replace(strstr($current_url, "?controller"), "?controller=".$_GET['controller']."&action=pjActionLogin&tab=candidate", $current_url);
		if($this->option_arr['o_employee_confirmed'] == 'no')
		{
			$params['return_failed'] = str_replace(strstr($current_url, "?controller"), "?controller=".$_GET['controller']."&action=pjActionLogin&tab=candidate&social_err=2", $current_url);
		}elseif($this->option_arr['o_employee_confirmed'] == 'manual'){
			$params['return_failed'] = str_replace(strstr($current_url, "?controller"), "?controller=".$_GET['controller']."&action=pjActionLogin&tab=candidate&social_err=3", $current_url);
		}
		$url_arr['facebook_candidate'] = $_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionSocial&" . http_build_query($params);

		$params['network'] = 'linkedin';
		$params['client_type'] = 'candidate';
		$url_arr['linkedin_candidate'] = $_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionSocial&" . http_build_query($params);
		
		$params['network'] = 'facebook';
		$params['client_type'] = 'employer';
		$params['return_success'] = PJ_INSTALL_URL . 'index.php?controller=pjAdmin&action=pjActionIndex';
		$params['return_failed'] = str_replace(strstr($current_url, "?controller"), "?controller=".$_GET['controller']."&action=pjActionLogin&tab=employer", $current_url);
		if($this->option_arr['o_employer_confirmed'] == 'no')
		{
			$params['return_failed'] = str_replace(strstr($current_url, "?controller"), "?controller=".$_GET['controller']."&action=pjActionLogin&tab=employer&social_err=2", $current_url);
		}elseif($this->option_arr['o_employer_confirmed'] == 'manual'){
			$params['return_failed'] = str_replace(strstr($current_url, "?controller"), "?controller=".$_GET['controller']."&action=pjActionLogin&tab=employer&social_err=4", $current_url);
		}else{
			$params['return_success'] = PJ_INSTALL_URL . 'index.php?controller=pjAdmin&action=pjActionIndex';
		}
		$url_arr['facebook_employer'] = $_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionSocial&" . http_build_query($params);
		
		$params['network'] = 'linkedin';
		$params['client_type'] = 'employer';
		$url_arr['linkedin_employer'] = $_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionSocial&" . http_build_query($params);
										
		return $url_arr;
	}
	
	public function getFacebookLoginUrl($return_success = '', $return_failed = '', $client = 'candidate')
	{
		$state = serialize(array('return_success' => $return_success, 'return_failed' => $return_failed, 'client' => $client, 'unique' => uniqid('', true)));
		$redirect_uri = PJ_INSTALL_URL . 'index.php?controller=pjLoad&action=pjActionFacebook';
		$facebook = new pjFacebook(
				$this->option_arr['o_facebook_api_key'],
				$this->option_arr['o_facebook_api_secret'],
				$redirect_uri
		);
		$loginUrl = $facebook->getLoginUrl();
		$_SESSION['facebook_state'] = $state;
		return $loginUrl;
	}
	
	public function getLinkedinLoginUrl($return_success = '', $return_failed = '', $client = 'candidate')
	{
		$state = serialize(array('return_success' => $return_success, 'return_failed' => $return_failed, 'client' => $client, 'unique' => uniqid('', true)));
		$redirect = PJ_INSTALL_URL . 'index.php?controller=pjLoad&action=pjActionLinkedin';
		$params = array(
			'response_type' => 'code',
			'client_id' => $this->option_arr['o_linkedin_api_key'],
			'scope' => $this->option_arr['o_linkedin_scope'],
			'state' => $state,
			'redirect_uri' => $redirect
		);
		$_SESSION['linkedin_state'] = $state;
		return 'https://www.linkedin.com/oauth/v2/authorization?' . http_build_query($params);
	}
	
	public function fetchLinkedin($resource, $access_token = '')
	{
		$pjHttp = new pjHttp();
		$pjHttp->setHeaders(array('Authorization' => 'Bearer ' . $access_token));
		$pjHttp->request('https://api.linkedin.com' . $resource);
		$response = $pjHttp->getResponse();
		return self::jsonDecode($response);
	}
	
	public function pjActionEmployeeConfirm()
	{
		$this->setLayout('pjActionConfirm');
		
		$pjEmployeeModel = pjEmployeeModel::factory();
		
		if (isset($_POST['confirm']))
		{
			$arr = $pjEmployeeModel->find($_POST['id'])->getData();
				
			if (count($arr) > 0)
			{
				$sql = "UPDATE `".$pjEmployeeModel->getTable()."` SET status = 'T' WHERE SHA1(CONCAT(`id`, `created`, '".PJ_SALT."')) = '" . $_POST['hash'] . "'";
		
				$pjEmployeeModel->reset()->execute($sql);
		
				$arr = $pjEmployeeModel->reset()->find($_POST['id'])->getData();
				
				pjUtil::redirect(PJ_INSTALL_URL . 'index.php?controller=pjLoad&action=pjActionEmployeeConfirm&err=200');
			}
		}else{
			if (isset($_GET['hash']) && isset($_GET['id']))
			{
				$arr = $pjEmployeeModel->find($_GET['id'])->getData();
				if (count($arr) == 0)
				{
					$this->set('status', 2);
				}else{
					if ($arr['status'] == 'T')
					{
						$this->set('status', 4);
					}else{
						$hash = sha1($arr['id'] . $arr['created'] . PJ_SALT);
						if ($_GET['hash'] != $hash)
						{
							$this->set('status', 3);
						}else{
							$this->set('arr', $arr);
						}
					}
				}
			}else if (!isset($_GET['err'])) {
				$this->set('status', 1);
			}
		}
	}
	public function pjActionEmployerConfirm()
	{
		$this->setLayout('pjActionConfirm');
	
		$pjEmployerModel = pjEmployerModel::factory();
	
		if (isset($_POST['confirm']))
		{
			$arr = $pjEmployerModel->find($_POST['id'])->getData();
	
			if (count($arr) > 0)
			{
				$sql = "UPDATE `".$pjEmployerModel->getTable()."` SET status = 'T' WHERE SHA1(CONCAT(`id`, `created`, '".PJ_SALT."')) = '" . $_POST['hash'] . "'";
	
				$pjEmployerModel->reset()->execute($sql);
	
				$arr = $pjEmployerModel->reset()->find($_POST['id'])->getData();
	
				pjUtil::redirect(PJ_INSTALL_URL . 'index.php?controller=pjLoad&action=pjActionEmployerConfirm&err=200');
			}
		}else{
			if (isset($_GET['hash']) && isset($_GET['id']))
			{
				$arr = $pjEmployerModel->find($_GET['id'])->getData();
				if (count($arr) == 0)
				{
					$this->set('status', 2);
				}else{
					if ($arr['status'] == 'T')
					{
						$this->set('status', 4);
					}else{
						$hash = sha1($arr['id'] . $arr['created'] . PJ_SALT);
						if ($_GET['hash'] != $hash)
						{
							$this->set('status', 3);
						}else{
							$this->set('arr', $arr);
						}
					}
				}
			}else if (!isset($_GET['err'])) {
				$this->set('status', 1);
			}
		}
	}
}
?>