<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminUsers extends pjAdmin
{
	public function pjActionCheckEmail()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (!isset($_GET['email']) || empty($_GET['email']))
			{
				echo 'false';
				exit;
			}
			$pjUserModel = pjUserModel::factory()->where('t1.email', $_GET['email']);
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$pjUserModel->where('t1.id !=', $_GET['id']);
			}
			echo $pjUserModel->findCount()->getData() == 0 ? 'true' : 'false';
		}
		exit;
	}
	
	public function pjActionCloneUser()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				$MultiLangModel = new pjMultiLangModel();

				$data = pjUserModel::factory()->whereIn('id', $_POST['record'])->findAll()->getData();
				foreach ($data as $item)
				{
					$item_id = $item['id'];
					unset($item['id']);
					unset($item['email']);

					$id = pjUserModel::factory($item)->insert()->getInsertId();
					if ($id !== false && (int) $id > 0)
					{
						$_data = pjMultiLangModel::factory()->getMultiLang($item_id, 'pjUser');
						$MultiLangModel->saveMultiLang($_data, $id, 'pjUser');
					}
				}
			}
		}
		exit;
	}
	
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			if (isset($_POST['user_create']))
			{
				$data = array();
				$data['is_active'] = 'T';
				$data['ip'] = $_SERVER['REMOTE_ADDR'];

				if($_POST['role_id'] != 1)
				{
					if(!isset($_POST['section_allow']))
					{
						$data['section_allow'] = '0';
					}else{
						$data['section_allow'] = '1';
					}
					if(!isset($_POST['file_allow']))
					{
						$data['file_allow'] = '0';
					}else{
						$data['file_allow'] = '1';
					}
				}
				unset($_POST['section_allow']);
				unset($_POST['file_allow']);

				$id = pjUserModel::factory(array_merge($_POST, $data))->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					if($_POST['role_id'] != 1)
					{
						$pjUserFileModel = pjUserFileModel::factory();
						if(isset($_POST['file_id']))
						{
							$pjUserFileModel->begin();
							foreach ($_POST['file_id'] as $file_id)
							{
								$data = array();
								$data['user_id'] = $id;
								$data['file_id'] = $file_id;
								$pjUserFileModel->reset()->setAttributes($data)->insert();
							}
							$pjUserFileModel->commit();
						}
						$pjUserSectionModel = pjUserSectionModel::factory();
						if(isset($_POST['section_id']))
						{
							$pjUserSectionModel->begin();
							foreach ($_POST['section_id'] as $section_id)
							{
								$data = array();
								$data['user_id'] = $id;
								$data['section_id'] = $section_id;
								$pjUserSectionModel->reset()->setAttributes($data)->insert();
							}
							$pjUserSectionModel->commit();
						}
					}
					
					$err = 'AU03';
				} else {
					$err = 'AU04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminUsers&action=pjActionIndex&err=$err");
			} else {
				
				$this->set('role_arr', pjRoleModel::factory()->orderBy('t1.id ASC')->findAll()->getData());
		
				$section_arr = pjSectionModel::factory()
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjSection' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'section_name'", 'left')
					->select('t1.*, t2.content AS section_name')
					->orderBy("section_name ASC")
					->findAll()
					->getData();
				$this->set('section_arr', $section_arr);
				
				$file_arr = pjFileModel::factory()
					->orderBy("file_name ASC")
					->findAll()
					->getData();
				$this->set('file_arr', $file_arr);
				
				$this->appendJs('jquery.multiselect.min.js', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendCss('jquery.multiselect.css', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminUsers.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteUser()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if ($_GET['id'] != $this->getUserId() && $_GET['id'] != 1)
			{
				if (pjUserModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
				{
					pjUserFileModel::factory()->where('user_id', $_GET['id'])->eraseAll();
					pjUserSectionModel::factory()->where('section_id', $_GET['id'])->eraseAll();
					$response['code'] = 200;
				} else {
					$response['code'] = 100;
				}
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteUserBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjUserModel::factory()
					->where('id !=', $this->getUserId())
					->where('id !=', 1)
					->whereIn('id', $_POST['record'])->eraseAll();
					
				pjUserFileModel::factory()->whereIn('file_id', $_POST['record'])->eraseAll();
				pjUserSectionModel::factory()->whereIn('section_id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionExportUser()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjUserModel::factory()->whereIn('id', $_POST['record'])->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Users-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionGetUser()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjUserModel = pjUserModel::factory();
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjUserModel->where('t1.email LIKE', "%$q%");
				$pjUserModel->orWhere('t1.name LIKE', "%$q%");
			}

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

			$total = $pjUserModel->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 = array();
			
			$data = $pjUserModel->select('t1.id, t1.email, t1.name, DATE(t1.created) AS created, t1.status, t1.is_active, t1.role_id, t2.role')
				->join('pjRole', 't2.id=t1.role_id', 'left')
				->orderBy("$column $direction")->limit($rowCount, $offset)->findAll()->getData();
				
			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('pjAdminUsers.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSetActive()
	{
		$this->setAjax(true);

		if ($this->isXHR())
		{
			$pjUserModel = pjUserModel::factory();
			
			$arr = $pjUserModel->find($_POST['id'])->getData();
			
			if (count($arr) > 0)
			{
				switch ($arr['is_active'])
				{
					case 'T':
						$sql_status = 'F';
						break;
					case 'F':
						$sql_status = 'T';
						break;
					default:
						return;
				}
				$pjUserModel->reset()->setAttributes(array('id' => $_POST['id']))->modify(array('is_active' => $sql_status));
			}
		}
		exit;
	}
	
	public function pjActionSaveUser()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjUserModel = pjUserModel::factory();
			
			$pass = true;
			if ((int) $_GET['id'] === 1 && in_array($_POST['column'], array('role_id', 'status', 'is_active')))
			{
				$pass = false;
			}
			if ($pass)
			{
				$pjUserModel->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
			}
		}
		exit;
	}
	
	public function pjActionStatusUser()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjUserModel::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['user_update']))
			{
				$data = array();
				if($_POST['role_id'] != 1)
				{
					if(!isset($_POST['section_allow']))
					{
						$data['section_allow'] = '0';
					}else{
						$data['section_allow'] = '1';
					}
					if(!isset($_POST['file_allow']))
					{
						$data['file_allow'] = '0';
					}else{
						$data['file_allow'] = '1';
					}
				}
				unset($_POST['section_allow']);
				unset($_POST['file_allow']);
				
				pjUserModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll(array_merge($_POST, $data));
				
				$pjUserFileModel = pjUserFileModel::factory();
				$pjUserSectionModel = pjUserSectionModel::factory();
				if($_POST['role_id'] != 1)
				{
					$pjUserFileModel->where('user_id', $_POST['id'])->eraseAll();
					if(isset($_POST['file_id']))
					{
						$pjUserFileModel->begin();
						foreach ($_POST['file_id'] as $file_id)
						{
							$data = array();
							$data['user_id'] = $_POST['id'];
							$data['file_id'] = $file_id;
							$pjUserFileModel->reset()->setAttributes($data)->insert();
						}
						$pjUserFileModel->commit();
					}
					$pjUserSectionModel->where('user_id', $_POST['id'])->eraseAll();
					if(isset($_POST['section_id']))
					{
						$pjUserSectionModel->begin();
						foreach ($_POST['section_id'] as $section_id)
						{
							$data = array();
							$data['user_id'] = $_POST['id'];
							$data['section_id'] = $section_id;
							$pjUserSectionModel->reset()->setAttributes($data)->insert();
						}
						$pjUserSectionModel->commit();
					}
				}else{
					$pjUserFileModel->where('user_id', $_POST['id'])->eraseAll();
					$pjUserSectionModel->where('user_id', $_POST['id'])->eraseAll();
				}
				
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminUsers&action=pjActionIndex&err=AU01");
				
			} else {
				$arr = pjUserModel::factory()
					->find($_GET['id'])
					->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminUsers&action=pjActionIndex&err=AU08");
				}
				$section_ids_arr = pjUserSectionModel::factory()
					->where('t1.user_id', $_GET['id'])
					->findAll()
					->getDataPair('section_id', 'section_id');
				$file_ids_arr = pjUserFileModel::factory()
					->where('t1.user_id', $_GET['id'])
					->findAll()
					->getDataPair('file_id', 'file_id');
					
				$this->set('arr', $arr);
				$this->set('section_ids_arr', $section_ids_arr);
				$this->set('file_ids_arr', $file_ids_arr);
				
				$this->set('role_arr', pjRoleModel::factory()->orderBy('t1.id ASC')->findAll()->getData());
				
				$section_arr = pjSectionModel::factory()
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjSection' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'section_name'", 'left')
					->select('t1.*, t2.content AS section_name')
					->orderBy("section_name ASC")
					->findAll()
					->getData();
				$this->set('section_arr', $section_arr);
				
				$file_arr = pjFileModel::factory()
					->orderBy("file_name ASC")
					->findAll()
					->getData();
				$this->set('file_arr', $file_arr);
				
				$this->appendJs('jquery.multiselect.min.js', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendCss('jquery.multiselect.css', PJ_THIRD_PARTY_PATH . 'multiselect/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminUsers.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
}
?>