<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdmin extends pjAppController
{
	public $requireLogin = true;
	
	public function __construct($requireLogin=null)
	{
		$this->setLayout('pjActionAdmin');
		
		if (!is_null($requireLogin) && is_bool($requireLogin))
		{
			$this->requireLogin = $requireLogin;
		}
		
		if ($this->requireLogin)
		{
			if (!$this->isLoged() && !in_array(@$_GET['action'], array('pjActionLogin', 'pjActionEmployerLogin', 'pjActionForgot', 'pjActionEmployerForgot', 'pjActionPreview', 'pjActionExportFeed')))
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin");
			}
		}
	}
	
	public function beforeRender()
	{
		
	}
		
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEmployer())
		{
			$pjJobModel = pjJobModel::factory();
			$pjEmployerModel = pjEmployerModel::factory();
			$pjEmployeeModel = pjEmployeeModel::factory();
			$pjApplicationModel = pjApplicationModel::factory();
			
			$cnt_views = 0;
			$popular_arr = array();
			$job_arr = array();
			if($this->isEmployer())
			{
				$employer_id = $this->getUserId();
				
				$pjApplicationModel->where("t1.job_id IN(SELECT `TJ`.`id` FROM `".$pjJobModel->getTable()."` AS `TJ` WHERE `TJ`.`employer_id` = $employer_id)");
				$_arr = $pjJobModel->reset()->where('t1.employer_id', $employer_id)->findAll()->getData();
				foreach($_arr as $v)
				{
					$cnt_views += $v['views'];
				}
				
				$pjJobModel->reset()->where('t1.employer_id', $employer_id);
				$job_arr = $pjJobModel->select('t1.id, t1.job_refid, t2.content as job_title, t1.expired, t1.status, t1.type_id, (SELECT COUNT(*) FROM `'.pjApplicationModel::factory()->getTable().'` as TA WHERE TA.job_id = t1.id) as cnt_applications')
						->join('pjMultiLang', "t2.model='pjJob' AND t2.foreign_id=t1.id AND t2.field='job_title' AND t2.locale='".$this->getLocaleId()."'", 'left')
						->orderBy("t1.created DESC")->limit(4, 0)->findAll()->getData();
						
				$pjJobModel->reset()->where('t1.employer_id', $employer_id);
				$popular_arr = $pjJobModel->select('t1.id, t1.job_refid, t2.content as job_title, t1.expired, t1.status, t1.type_id, t1.views')
						->join('pjMultiLang', "t2.model='pjJob' AND t2.foreign_id=t1.id AND t2.field='job_title' AND t2.locale='".$this->getLocaleId()."'", 'left')
						->orderBy("t1.views DESC")->limit(4, 0)->findAll()->getData();		
				
			}else{
				$job_arr = $pjJobModel->select('t1.id, t1.job_refid, t2.content as job_title, t1.expired, t1.status, t1.type_id, (SELECT COUNT(*) FROM `'.pjApplicationModel::factory()->getTable().'` as TA WHERE TA.job_id = t1.id) as cnt_applications')
						->join('pjMultiLang', "t2.model='pjJob' AND t2.foreign_id=t1.id AND t2.field='job_title' AND t2.locale='".$this->getLocaleId()."'", 'left')
						->orderBy("t1.created DESC")->limit(4, 0)->findAll()->getData();
			}
					
			$cnt_employers = $pjEmployerModel->where('t1.status', 'T')->findCount()->getData();
			$cnt_jobs = $pjJobModel->where("(t1.status='T' OR t1.status='E')")->findCount()->getData();
			$cnt_applications = $pjApplicationModel->where('t1.status', 'T')->findCount()->getData();
						
			$employer_arr = $pjEmployerModel->select('t1.id, t1.email, t1.company_name, t1.thumb, t1.status, (SELECT COUNT(*) FROM `'.pjJobModel::factory()->getTable().'` as t2 WHERE t2.employer_id = t1.id) as cnt_jobs')
				->orderBy("t1.created DESC")->limit(3, 0)->findAll()->getData();

			$application_arr = $pjApplicationModel->select('t1.*')
				->orderBy("t1.created DESC")->limit(6, 0)->findAll()->getData();	
				
			$this->set('cnt_jobs', $cnt_jobs);
			$this->set('cnt_employers', $cnt_employers);
			$this->set('cnt_applications', $cnt_applications);
			$this->set('cnt_views', $cnt_views);
			
			$this->set('job_arr', $job_arr);
			$this->set('popular_arr', $popular_arr);
			$this->set('employer_arr', $employer_arr);
			$this->set('application_arr', $application_arr);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionForgot()
	{
		$this->setLayout('pjActionAdminLogin');
		
		if (isset($_POST['forgot_user']))
		{

			if (!isset($_POST['forgot_email']) || !pjValidation::pjActionNotEmpty($_POST['forgot_email']) || !pjValidation::pjActionEmail($_POST['forgot_email']))
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionForgot&err=AA10");
			}
			$pjUserModel = pjUserModel::factory();
			$user = $pjUserModel
				->where('t1.email', $_POST['forgot_email'])
				->limit(1)
				->findAll()
				->getData();
				
			if (count($user) != 1)
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionForgot&err=AA10");
			} else {
				$user = $user[0];
				
				$Email = new pjEmail();
				$Email
					->setTo($user['email'])
					->setFrom($user['email'])
					->setSubject(__('emailForgotSubject', true));
				
				if ($this->option_arr['o_send_email'] == 'smtp')
				{
					$Email
						->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'])
					;
				}
				
				$body = str_replace(
					array('{Name}', '{Password}'),
					array($user['name'], $user['password']),
					__('emailForgotBody', true)
				);

				if ($Email->send($body))
				{
					$err = "AA11";
				} else {
					$err = "AA12";
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionForgot&err=$err");
			}
		} else {
			$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
			$this->appendJs('pjAdmin.js');
		}
	}
	
	public function pjActionEmployerForgot()
	{
		$this->setLayout('pjActionAdminLogin');
		
		if (isset($_POST['forgot_employer']))
		{
			if (!isset($_POST['forgot_email']) || !pjValidation::pjActionNotEmpty($_POST['forgot_email']) || !pjValidation::pjActionEmail($_POST['forgot_email']))
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionEmployerForgot&err=AA10");
			}
			$pjEmployerModel = pjEmployerModel::factory();
			$employer = $pjEmployerModel
				->where('t1.email', $_POST['forgot_email'])
				->limit(1)
				->findAll()
				->getData();
				
			if (count($employer) != 1)
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionEmployerForgot&err=AA10");
			} else {
				$employer = $employer[0];
				
				$Email = new pjEmail();
				$Email
					->setTo($employer['email'])
					->setFrom($employer['email'])
					->setSubject(__('emailForgotSubject', true));
				
				if ($this->option_arr['o_send_email'] == 'smtp')
				{
					$Email
						->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'])
					;
				}

				
				$body = str_replace(
					array('{Name}', '{Password}'),
					array($employer['contact_name'], $employer['password']),
					__('emailForgotBody', true)
				);

				if ($Email->send($body))
				{
					$err = "AA11";
				} else {
					$err = "AA12";
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionEmployerForgot&err=$err");
			}
		} else {
			$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
			$this->appendJs('pjAdmin.js');
		}
	}
	
	public function pjActionMessages()
	{
		$this->setAjax(true);
		header("Content-Type: text/javascript; charset=utf-8");
	}
	
	public function pjActionLogin()
	{
		$this->setLayout('pjActionAdminLogin');
		
		if (isset($_POST['login_user']))
		{
			if (!isset($_POST['login_email']) || !isset($_POST['login_password']) ||
				!pjValidation::pjActionNotEmpty($_POST['login_email']) ||
				!pjValidation::pjActionNotEmpty($_POST['login_password']) ||
				!pjValidation::pjActionEmail($_POST['login_email']))
			{
				// Data not validate
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=4");
			}
			$pjUserModel = pjUserModel::factory();

			$user = $pjUserModel
				->where('t1.email', $_POST['login_email'])
				->where(sprintf("t1.password = AES_ENCRYPT('%s', '%s')", $pjUserModel->escapeStr($_POST['login_password']), PJ_SALT))
				->limit(1)
				->findAll()
				->getData();

			if (count($user) != 1)
			{
				# Login failed
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=1");
			} else {
				$user = $user[0];
				unset($user['password']);
															
				if (!in_array($user['role_id'], array(1,2,3)))
				{
					# Login denied
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=2");
				}
				
				if ($user['role_id'] == 3 && $user['is_active'] == 'F')
				{
					# Login denied
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=2");
				}
				
				if ($user['status'] != 'T')
				{
					# Login forbidden
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=3");
				}
				
				# Login succeed
				$last_login = date("Y-m-d H:i:s");
    			$_SESSION[$this->defaultUser] = $user;
    			
    			# Update
    			$data = array();
    			$data['last_login'] = $last_login;
    			$pjUserModel->reset()->setAttributes(array('id' => $user['id']))->modify($data);

    			if ($this->isAdmin())
    			{
	    			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionIndex");
    			}
			}
		} else {
			$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
			$this->appendJs('pjAdmin.js');
		}
	}
	
	public function pjActionEmployerLogin()
	{
		$this->setLayout('pjActionAdminLogin');
		
		if (isset($_POST['login_employer']))
		{
			if (!isset($_POST['login_email']) || !isset($_POST['login_password']) ||
				!pjValidation::pjActionNotEmpty($_POST['login_email']) ||
				!pjValidation::pjActionNotEmpty($_POST['login_password']) ||
				!pjValidation::pjActionEmail($_POST['login_email']))
			{
				// Data not validate
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionEmployerLogin&err=4");
			}
			$pjEmployerModel = pjEmployerModel::factory();

			$employer = $pjEmployerModel
				->where('t1.email', $_POST['login_email'])
				->where(sprintf("t1.password = AES_ENCRYPT('%s', '%s')", $pjEmployerModel->escapeStr($_POST['login_password']), PJ_SALT))
				->limit(1)
				->findAll()
				->getData();

			if (count($employer) != 1)
			{
				# Login failed
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionEmployerLogin&err=1");
			} else {
				$employer = $employer[0];
				$employer['is_employer'] = true;
				unset($employer['password']);
															
				if ($employer['status'] != 'T')
				{
					# Login forbidden
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionEmployerLogin&err=3");
				}
				
				# Login succeed
				$last_login = date("Y-m-d H:i:s");
    			$_SESSION[$this->defaultUser] = $employer;
    			
    			# Update
    			$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($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionIndex");
    			}
			}
		} else {
			$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
			$this->appendJs('pjAdmin.js');
		}
	}
	
	public function pjActionLogout()
	{

		$is_employer = false;
		if ($this->isLoged())
        {
        	$is_employer = $this->isEmployer();
        	unset($_SESSION[$this->defaultUser]);
        }
        if($is_employer == true)
        {
        	if(!empty($this->option_arr['o_job_page']))
        	{
        		pjUtil::redirect($this->option_arr['o_job_page']);
        	}else{
        		pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionEmployerLogin");
        	}
        }else{
        	pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin");
        }
	}
	
	public function pjActionProfile()
	{
		$this->checkLogin();
		
		if (!$this->isAdmin())
		{
			if (isset($_POST['profile_update']))
			{
				$pjUserModel = pjUserModel::factory();
				$arr = $pjUserModel->find($this->getUserId())->getData();
				$data = array();
				$data['role_id'] = $arr['role_id'];
				$data['status'] = $arr['status'];
				$post = array_merge($_POST, $data);
				if (!$pjUserModel->validates($post))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionProfile&err=AA14");
				}
				$pjUserModel->set('id', $this->getUserId())->modify($post);
				
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionProfile&err=AA13");
			} else {
				$this->set('arr', pjUserModel::factory()->find($this->getUserId())->getData());
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdmin.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSetLocale()
	{
		if (isset($_GET['id']) && (int) $_GET['id'] > 0 )
		{
			$this->setLocaleId($_GET['id']);
		}
		pjUtil::redirect(sprintf("%sindex.php?controller=pjAdmin&action=pjActionIndex", PJ_INSTALL_URL));
	}
}
?>