<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminApplications extends pjAdmin
{
	public function pjActionDeleteApplication()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if ($_GET['id'])
			{
				$pjApplicationModel = pjApplicationModel::factory();
				
				$valid = true;
				if($this->isEmployer())
				{
					$application_id_arr = $this->getApplicationId($this->getUserId());
					if(!in_array($_GET['id'], $application_id_arr))
					{
						$valid = false;
					}
				}
				
				if($valid == true)
				{
					if ($pjApplicationModel->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
					{
						pjMultiLangModel::factory()->where('model', 'pjApplication')->where('foreign_id', $_GET['id'])->eraseAll();
						$pjFileModel = pjFileModel::factory();
						$file_arr = $pjFileModel->where("`file_type`", 'application')->where("`foreign_id`", $_GET['id'])->findAll()->getData();
						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()->setAttributes(array('id' => $file_arr[0]['id']))->erase();
						}
						
						$response['code'] = 200;
					} else {
						$response['code'] = 100;
					}
				}else{
					$response['code'] = 100;
				}
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteApplicationBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjApplicationModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
				pjMultiLangModel::factory()->where('model', 'pjApplication')->whereIn('foreign_id', $_POST['record'])->eraseAll();
				
				$pjFileModel = pjFileModel::factory();
				$file_arr = $pjFileModel->where("`file_type`", 'application')->whereIn("`foreign_id`", $_POST['record'])->findAll()->getData();
				if(!empty($file_arr)){
					foreach($file_arr as $f)
					{
						if (!empty($f['file_path']) && is_file(PJ_INSTALL_PATH . $f['file_path']))
						{
							@unlink(PJ_INSTALL_PATH . $f['file_path']);
						}
						$pjFileModel->reset()->setAttributes(array('id' => $f['id']))->erase();
					}
				}
			}
		}
		exit;
	}
	
	public function pjActionExportApplication()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjApplicationModel::factory()->whereIn('id', $_POST['record'])->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Applications-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionGetApplication()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjApplicationModel = pjApplicationModel::factory();
			if ($this->isEmployer())
			{
				$pjApplicationModel->where('t1.job_id IN(SELECT t3.id FROM `' . pjJobModel::factory()->getTable() . '` as t3 WHERE t3.employer_id = ' .$this->getUserId(). ')');
			}
			if (isset($_GET['job_id']))
			{
				$pjApplicationModel->where('t1.job_id', $_GET['job_id']);
			}
			if (isset($_GET['employer_id']) && $_GET['employer_id'] != '')
			{
				$employer_id = $pjApplicationModel->escapeStr($_GET['employer_id']);
				$pjApplicationModel->where('t1.job_id IN(SELECT t3.id FROM `' . pjJobModel::factory()->getTable() . '` as t3 WHERE t3.employer_id = ' .$employer_id. ')');
			}
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = $pjApplicationModel->escapeStr($_GET['q']);
				$q = str_replace(array('%', '_'), array('\%', '\_'), trim($q));
				$pjApplicationModel->where('(t1.email LIKE "%'.$q.'%" OR t1.fname LIKE "%'.$q.'%" OR t1.lname LIKE "%'.$q.'%")');
			}

			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('T', 'F','N')))
			{
				$pjApplicationModel->where('t1.status', $_GET['status']);
			}
				
			$column = 'fname';
			$direction = 'ASC';
			$allowed_columns = array('job_refid', 'name', 'email', 'created', '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 = $pjApplicationModel->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 = $pjApplicationModel->select('t1.id, t1.job_id, t1.email, t1.fname, t1.lname, DATE(t1.created) AS created, t1.status, t2.job_refid')
				->join('pjJob', 't2.id=t1.job_id', 'left')
				->orderBy("$column $direction")->limit($rowCount, $offset)->findAll()->getData();
			foreach($data as $k => $v)
			{
				$name_arr = array();
				if(!empty($v['fname']))
				{
					$name_arr[] = pjSanitize::html($v['fname']);
				}
				if(!empty($v['lname']))
				{
					$name_arr[] = pjSanitize::html($v['lname']);
				}
				$v['name'] = join(" ", $name_arr);
				$data[$k] = $v;
			}
			$data = pjSanitize::clean($data);
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEmployer())
		{
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminApplications.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}

	public function pjActionSaveApplication()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjApplicationModel = pjApplicationModel::factory();
			
			$pjApplicationModel->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
			
		}
		exit;
	}
	
	public function pjActionStatusApplication()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjApplicationModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array(
					'status' => ":IF(`status`='F','T','F')"
				));
			}
		}
		exit;
	}
	
	public function pjActionView()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEmployer())
		{
			if($this->isEmployer())
			{
				$application_id_arr = $this->getApplicationId($this->getUserId());
				if(!in_array($_GET['id'], $application_id_arr))
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminApplications&action=pjActionIndex");
				}
			}
			
			$pjApplicationModel = pjApplicationModel::factory();
			
			$id = $_GET['id'];
			
			$arr = $pjApplicationModel
				->select('t1.*, t2.job_refid, t3.content AS job_title, t4.content AS notes, t6.phone, t6.linkedin,
							t5.file_name AS filename1, t5.file_path AS filepath1, t5.hash AS hash1, t5.id AS fileid1,
							t7.file_name AS filename2, t7.file_path AS filepath2, t7.hash AS hash2, t7.id AS fileid2,
							t8.company_name, t2.employer_id')
				->join('pjJob', 't2.id=t1.job_id', 'left')
				->join('pjMultiLang', "t3.model='pjJob' AND t3.foreign_id=t2.id AND t3.field='job_title' AND t3.locale='".$this->getLocaleId()."'", 'left')
				->join('pjMultiLang', "t4.model='pjApplication' AND t4.foreign_id=t1.id AND t4.field='notes' AND t4.locale='".$this->getLocaleId()."'", 'left')
				->join('pjFile', "t5.foreign_id=t1.id AND t5.file_type='application'", 'left')
				->join('pjEmployee', "t6.id=t1.employee_id", 'left')
				->join('pjFile', "t7.foreign_id=t6.id AND t7.file_type='employee'", 'left')
				->join('pjEmployer', "t8.id=t2.employer_id", 'left')
				->find($id)
				->getData();
			$this->set('arr', $arr);		
					
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminApplications.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}
}
?>