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

	
		if ($this->isXHR())
		{
			if (!isset($_GET['email']) || empty($_GET['email']))
			{
				echo 'false';
				exit;
			}
			$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 pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			if (isset($_POST['employee_create']))
			{
				$data = array();
				$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();
						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($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();
							}
						}
					}
					$err = 'AEE03';
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjEmployee');
					}
				} else {
					$err = 'AEE04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminEmployees&action=pjActionIndex&err=$err");
			} else {
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('additional-methods.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminEmployees.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteEmployee()
	{
		$this->setAjax(true);

	
		if ($this->isXHR())
		{
			$response = array();
			if ($_GET['id'])
			{
				if (pjEmployeeModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
				{
					pjMultiLangModel::factory()->where('model', 'pjEmployee')->where('foreign_id', $_GET['id'])->eraseAll();
					$pjFileModel = pjFileModel::factory();
					$file_arr = $pjFileModel->where("`file_type`", 'employee')->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;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteEmployeeBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjEmployeeModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
				pjMultiLangModel::factory()->where('model', 'pjEmployee')->whereIn('foreign_id', $_POST['record'])->eraseAll();
				
				$pjFileModel = pjFileModel::factory();
				$file_arr = $pjFileModel->where("`file_type`", 'employee')->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 pjActionExportEmployee()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjEmployeeModel::factory()->whereIn('id', $_POST['record'])->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Employees-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionGetEmployee()
	{
		$this->setAjax(true);

	
		if ($this->isXHR())
		{
			$pjEmployeeModel = pjEmployeeModel::factory();
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = $pjEmployeeModel->escapeStr($_GET['q']);
				$q = str_replace(array('%', '_'), array('\%', '\_'), trim($q));
				$pjEmployeeModel->where('t1.email LIKE', "%$q%");
				$pjEmployeeModel->orWhere('t1.fname LIKE', "%$q%");
				$pjEmployeeModel->orWhere('t1.lname LIKE', "%$q%");
			}

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

	public function pjActionSaveEmployee()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjEmployeeModel = pjEmployeeModel::factory();
			
			$pjEmployeeModel->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
			$this->updateEmployee($_GET['id']);
			
		}
		exit;
	}
	
	public function pjActionStatusEmployee()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjEmployeeModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array(
					'status' => ":IF(`status`='F','T','F')"
				));
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{

				
			if (isset($_POST['employee_update']))
			{
				pjEmployeeModel::factory()->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();
					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($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();
					}
				}
				$this->updateEmployee($_POST['id']);
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminEmployees&action=pjActionIndex&err=AEE01");
				
			} else {
				$arr = pjEmployeeModel::factory()->find($_GET['id'])->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminEmployees&action=pjActionIndex&err=AEE08");
				}
				$file_arr = pjFileModel::factory()->where("`file_type`", 'employee')->where("`foreign_id`", $_GET['id'])->findAll()->getData();
				
				if(!empty($file_arr)){
					$this->set('file_arr', $file_arr[0]);
				}
				
				$this->set('arr', $arr);
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('additional-methods.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminEmployees.js');
			}
		} else {
			$this->set('status', 2);
		}
	}

	public function pjActionView()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEmployer())
		{
			$arr = pjEmployeeModel::factory()->find($_GET['id'])->getData();
			if (count($arr) === 0)
			{
				pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminEmployees&action=pjActionIndex&err=AEE08");
			}
			$file_arr = pjFileModel::factory()->where("`file_type`", 'employee')->where("`foreign_id`", $_GET['id'])->findAll()->getData();
			
			if(!empty($file_arr)){
				$this->set('file_arr', $file_arr[0]);
			}
			
			$this->set('arr', $arr);
			
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteCV()
	{
		$this->setAjax(true);
		
		$pjFileModel = pjFileModel::factory();
		
		$arr = $pjFileModel->find($_POST['id'])->getData();
		
		$json_arr = array();
		if(!empty($arr))
		{
			if ($pjFileModel->reset()->setAttributes(array('id' => $_POST['id']))->erase()->getAffectedRows() == 1){
				if (!empty($arr['file_path']) && is_file(PJ_INSTALL_PATH . $arr['file_path']))
				{
					@unlink(PJ_INSTALL_PATH . $arr['file_path']);
				}
				$json_arr['status'] = 1;
			}else{
				$json_arr['status'] = 0;
			}
		}else{
			$json_arr['status'] = 0;
		}
		pjAppController::jsonResponse($json_arr);		
	}
	
	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;
	}
}
?>