<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminMembers extends pjAdmin
{
	private $imageFiles = array('small_path', 'medium_path', 'large_path', 'source_path');
	
	public function pjActionCheckEmail()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (!isset($_GET['email']) || empty($_GET['email']))
			{
				echo 'false';
				exit;
			}
			$pjMemberModel = pjMemberModel::factory()->where('t1.email', $_GET['email']);
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$pjMemberModel->where('t1.id !=', $_GET['id']);
			}
			echo $pjMemberModel->findCount()->getData() == 0 ? 'true' : 'false';
		}
		exit;
	}
	
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			$post_max_size = pjUtil::getPostMaxSize();
			if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && (int) $_SERVER['CONTENT_LENGTH'] > $post_max_size)
			{
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminMembers&action=pjActionIndex&err=AM05");
			}
			if (isset($_POST['member_create']))
			{
				pjAppController::validateCsrfToken();
				$data = array();
				$data['ip'] = pjUtil::getClientIp();
				$id = pjMemberModel::factory(array_merge($_POST, $data))->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					if(isset($_POST['skill_id']))
					{
						$pjMemberSkillModel = pjMemberSkillModel::factory();
						$pjMemberSkillModel->begin();
						foreach ($_POST['skill_id'] as $skill_id){
							$data = array();
							$data['member_id'] = $id;
							$data['skill_id'] = $skill_id;
							$pjMemberSkillModel->reset()->setAttributes($data)->insert();
						}
						$pjMemberSkillModel->commit();
					}
					
					if (isset($_POST['i18n']))
					{
				pjAppController::validateCsrfToken();
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjMember', 'data');
					}
					if (isset($_FILES['avatar']) && !empty($_FILES['avatar']['tmp_name']))
					{
						$Image = new pjImage();
						if ($Image->getErrorCode() !== 200)
						{
							$Image->setAllowedTypes(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg'));
							if ($Image->load($_FILES['avatar']))
							{
								$resp = $Image->isConvertPossible();
								if ($resp['status'] === true)
								{
									$hash = md5(uniqid(rand(), true));
									$image_path = PJ_UPLOAD_PATH . 'avatars/' . $id . '_' . $hash . '.' . $Image->getExtension();
										
									$Image->loadImage();
									$Image->setFillColor($this->imageFillColor);
									$Image->resizeSmart(96, 96);
									$Image->saveImage($image_path);
									
									$data = array();
									$data['avatar_path'] = $image_path;
									$data['mime_type'] = $_FILES['avatar']['type'];
									$data['avatar_hash'] = $hash;
										
									pjMemberModel::factory()->where('id', $id)->limit(1)->modifyAll($data);
								}
							}else{
								pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminMembers&action=pjActionIndex&err=AM06");
							}
						}
					}
					
					$err = 'AM03';
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminMembers&action=pjActionUpdate&id=$id&err=$err");
				} else {
					$err = 'AM04';
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminMembers&action=pjActionIndex&err=$err");
				}
				
			} else {
				$locale_arr = pjLocaleModel::factory()->select('t1.*, t2.file')
					->join('pjLocaleLanguage', 't2.iso=t1.language_iso', 'left')
					->where('t2.file IS NOT NULL')
					->orderBy('t1.sort ASC')->findAll()->getData();
						
				$lp_arr = array();
				foreach ($locale_arr as $item)
				{
					$lp_arr[$item['id']."_"] = $item['file'];
				}
				$this->set('lp_arr', $locale_arr);
				$this->set('locale_str', pjAppController::jsonEncode($lp_arr));
		
				$country_arr = pjCountryModel::factory()
					->select('t1.id, t2.content AS country_title')
					->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->orderBy('`country_title` ASC')
					->findAll()
					->getData();
				$this->set('country_arr', $country_arr);
				
				$skill_arr = pjSkillModel::factory()
					->select('t1.id, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjSkill' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('t1.status', 'T')
					->orderBy('`name` ASC')
					->findAll()
					->getData();
				$this->set('skill_arr', $skill_arr);
				
				$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('additional-methods.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
				$this->appendJs('jquery.tipsy.js', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendCss('jquery.tipsy.css', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendJs('pjAdminMembers.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
		
	public function pjActionDeleteMember()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			pjAppController::validateCsrfToken();
			$response = array();
			$pjMemberModel = pjMemberModel::factory();
			$arr = $pjMemberModel->find($_GET['id'])->getData();
			if (pjMemberModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				pjMemberSkillModel::factory()->where('member_id', $_GET['id'])->eraseAll();
				pjMultiLangModel::factory()->where('model', 'pjMember')->where('foreign_id', $_GET['id'])->eraseAll();
				@clearstatcache();
				if (!empty($arr['avatar_path']) && is_file(PJ_INSTALL_PATH . $arr['avatar_path']))
				{
					@unlink(PJ_INSTALL_PATH . $arr['avatar_path']);
				}
				$pjGalleryModel = pjGalleryModel::factory();
				$gallery_arr = $pjGalleryModel->where('foreign_id', $_GET['id'])->findAll()->getData();
				if (count($gallery_arr) > 0)
				{
					foreach ($gallery_arr as $item)
					{
						foreach ($this->imageFiles as $file)
						{
							@clearstatcache();
							if (!empty($item[$file]) && is_file($item[$file]))
							{
								@unlink($item[$file]);
							}
						}
					}
					$pjGalleryModel->eraseAll();
				}
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteMemberBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			pjAppController::validateCsrfToken();
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				$pjMemberModel = pjMemberModel::factory();
				$arr = $pjMemberModel->whereIn('id', $_POST['record'])->findAll()->getData();
				$pjMemberModel->reset()->whereIn('id', $_POST['record'])->eraseAll();
				pjMemberSkillModel::factory()->whereIn('member_id', $_POST['record'])->eraseAll();
				pjMultiLangModel::factory()->where('model', 'pjMember')->whereIn('foreign_id', $_POST['record'])->eraseAll();
				foreach($arr as $v)
				{
					@clearstatcache();
					if (!empty($v['avatar_path']) && is_file(PJ_INSTALL_PATH . $v['avatar_path']))
					{
						@unlink(PJ_INSTALL_PATH . $v['avatar_path']);
					}
				}
				$gallery_arr = pjGalleryModel::factory()->whereIn('foreign_id', $_POST['record'])->findAll()->getData();
				if (!empty($gallery_arr))
				{
					pjGalleryModel::factory()->whereIn('foreign_id', $_POST['record'])->eraseAll();
					foreach ($gallery_arr as $item)
					{
						foreach ($this->imageFiles as $file)
						{
							@clearstatcache();
							if (!empty($item[$file]) && is_file($item[$file]))
							{
								@unlink($item[$file]);
							}
						}
					}
				}
			}
		}
		exit;
	}
	
	public function pjActionGetMember()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjMemberModel = pjMemberModel::factory()
				->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjMember' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'biography'", 'left')
				->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjMember' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'name'", 'left')
				->join('pjMultiLang', "t4.foreign_id = t1.id AND t4.model = 'pjMember' AND t4.locale = '".$this->getLocaleId()."' AND t4.field = 'address'", 'left')
				->join('pjMultiLang', "t5.foreign_id = t1.id AND t5.model = 'pjMember' AND t5.locale = '".$this->getLocaleId()."' AND t5.field = 'city'", 'left')
				->join('pjMultiLang', "t6.foreign_id = t1.id AND t6.model = 'pjMember' AND t6.locale = '".$this->getLocaleId()."' AND t6.field = 'state'", 'left');
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjMemberModel->where("t3.content LIKE '%$q%' OR t1.email LIKE '%$q%' OR t2.content LIKE '%$q%'");
			}

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

			$total = $pjMemberModel->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 = $pjMemberModel
				->select("	t1.id, t1.email, t1.phone, t1.age, t1.zip, t1.created, t1.status, t1.last_login,
							t3.content as name, 
							t4.content as address, 
							t5. content as city, 
							t6.content as state"
						)
				->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->isEditor())
		{
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminMembers.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveMember()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			pjAppController::validateCsrfToken();
			$pjMemberModel = pjMemberModel::factory();
			if (!in_array($_POST['column'], $pjMemberModel->i18n))
			{
				$pjMemberModel->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
			} else {
				$pjMultiLangModel = pjMultiLangModel::factory();
				$cnt = $pjMultiLangModel	
							->where('t1.foreign_id !=', $_GET['id'])
							->where('t1.model', 'pjMember')
							->where('t1.locale', $this->getLocaleId())
							->where('t1.field', 'name')
							->where('t1.content', $_POST['value'])
							->findCount()
							->getData();
							
				if($cnt == 0)
				{
					$pjMultiLangModel->reset()->updateMultiLang(array($this->getLocaleId() => array($_POST['column'] => $_POST['value'])), $_GET['id'], 'pjMember', 'data');
				}
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();

		if ($this->isAdmin() || $this->isEditor())
		{
			$post_max_size = pjUtil::getPostMaxSize();
			if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && (int) $_SERVER['CONTENT_LENGTH'] > $post_max_size)
			{
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminMembers&action=pjActionIndex&err=AM09");
			}
			if (isset($_POST['member_update']))
			{
				pjAppController::validateCsrfToken();
				$data = array();
				$data['ip'] = pjUtil::getClientIp();
				$data['modified'] = date('Y-m-d H:i:s');
				
				$pjMemberModel = pjMemberModel::factory();
				$arr = $pjMemberModel->find($_POST['id'])->getData();
				$pjMemberModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll(array_merge($_POST, $data));
				if (isset($_POST['i18n']))
				{
				pjAppController::validateCsrfToken();
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjMember', 'data');
				}
				
				$pjMemberSkillModel = pjMemberSkillModel::factory();
				$pjMemberSkillModel->where('member_id', $_POST['id'])->eraseAll();
				if(isset($_POST['skill_id']))
				{
					$pjMemberSkillModel->reset()->begin();
					foreach ($_POST['skill_id'] as $skill_id){
						$data = array();
						$data['member_id'] = $_POST['id'];
						$data['skill_id'] = $skill_id;
						$pjMemberSkillModel->reset()->setAttributes($data)->insert();
					}
					$pjMemberSkillModel->commit();
				}

				if (isset($_FILES['avatar']) && !empty($_FILES['avatar']['tmp_name']))
				{
					$Image = new pjImage();
					if ($Image->getErrorCode() !== 200)
					{
						$Image->setAllowedTypes(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg'));
						if ($Image->load($_FILES['avatar']))
						{
							$resp = $Image->isConvertPossible();
							if ($resp['status'] === true)
							{
								if (!empty($arr['avatar_path']) && is_file(PJ_INSTALL_PATH . $arr['avatar_path']))
								{
									@unlink(PJ_INSTALL_PATH . $arr['avatar_path']);
								}
								$hash = md5(uniqid(rand(), true));
								$image_path = PJ_UPLOAD_PATH . 'avatars/' . $_POST['id'] . '_' . $hash . '.' . $Image->getExtension();
				
								$Image->loadImage();
								$Image->setFillColor($this->imageFillColor);
								$Image->resizeSmart(96, 96);
								$Image->saveImage($image_path);
									
								$data = array();
								$data['avatar_path'] = $image_path;
								$data['mime_type'] = $_FILES['avatar']['type'];
								$data['avatar_hash'] = $hash;
				
								$pjMemberModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll($data);
							}
						}else{
							pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminMembers&action=pjActionIndex&err=AM10");
						}
					}
				}
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminMembers&action=pjActionUpdate&id=".$_POST['id']."&err=AM01");
			} else {
				$arr = pjMemberModel::factory()->find($_GET['id'])->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminMembers&action=pjActionIndex&err=AM08");
				}
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjMember');
				$this->set('arr', $arr);
				
				$locale_arr = pjLocaleModel::factory()->select('t1.*, t2.file')
					->join('pjLocaleLanguage', 't2.iso=t1.language_iso', 'left')
					->where('t2.file IS NOT NULL')
					->orderBy('t1.sort ASC')->findAll()->getData();
				
				$lp_arr = array();
				foreach ($locale_arr as $item)
				{
					$lp_arr[$item['id']."_"] = $item['file'];
				}
				$this->set('lp_arr', $locale_arr);
				$this->set('locale_str', pjAppController::jsonEncode($lp_arr));
				
				$country_arr = pjCountryModel::factory()
					->select('t1.id, t2.content AS country_title')
					->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->orderBy('`country_title` ASC')
					->findAll()
					->getData();
				$this->set('country_arr', $country_arr);
				
				$skill_arr = pjSkillModel::factory()
					->select('t1.id, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjSkill' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('t1.status', 'T')
					->orderBy('`name` ASC')
					->findAll()
					->getData();
				$this->set('skill_arr', $skill_arr);
				$this->set('skill_id_arr', pjMemberSkillModel::factory()->where('t1.member_id', $_GET['id'])->findAll()->getDataPair(null, 'skill_id'));
				
				# Gallery plugin
				$this->appendCss('pj-gallery.css', pjObject::getConstant('pjGallery', 'PLUGIN_CSS_PATH'));
				$this->appendJs('ajaxupload.js', pjObject::getConstant('pjGallery', 'PLUGIN_JS_PATH'));
				$this->appendJs('jquery.gallery.js', pjObject::getConstant('pjGallery', 'PLUGIN_JS_PATH'));
				
				$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('additional-methods.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
				$this->appendJs('jquery.tipsy.js', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendCss('jquery.tipsy.css', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendJs('pjAdminMembers.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteAvatar()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			pjAppController::validateCsrfToken();
			$response = array();
			if (isset($_GET['id']))
			{
				$pjMemberModel = pjMemberModel::factory();
				$arr = $pjMemberModel->find($_GET['id'])->getData();
				@clearstatcache();
				if (!empty($arr['avatar_path']) && is_file(PJ_INSTALL_PATH . $arr['avatar_path']))
				{
					@unlink(PJ_INSTALL_PATH . $arr['avatar_path']);
				}
				$pjMemberModel->reset()->where('id', $_GET['id'])->limit(1)->modifyAll(array('avatar_path' => ':NULL', 'mime_type' => ':NULL', 'avatar_hash' => ':NULL'));
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionExport()
	{
		$this->checkLogin();
	
		if ($this->isAdmin() || $this->isEditor())
		{
			if(isset($_POST['members_export']))
			{
				$pjMemberModel = pjMemberModel::factory()
					->select(	
								"t1.id, 
								t1.email, AES_DECRYPT(t1.password, '".PJ_SALT."') AS `password`,
								t3.content as name, t1.phone, t1.age,
								t4.content as address, 
								t5. content as city, 
								t6.content as state,
								t1.zip, t1.country_id,
								t1.facebook, t1.google, t1.linkedin, t1.twitter,
								t2.content as biography,
								t1.modified, t1.created, t1.last_login, t1.status"
							)
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjMember' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'biography'", 'left')
					->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjMember' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'name'", 'left')
					->join('pjMultiLang', "t4.foreign_id = t1.id AND t4.model = 'pjMember' AND t4.locale = '".$this->getLocaleId()."' AND t4.field = 'address'", 'left')
					->join('pjMultiLang', "t5.foreign_id = t1.id AND t5.model = 'pjMember' AND t5.locale = '".$this->getLocaleId()."' AND t5.field = 'city'", 'left')
					->join('pjMultiLang', "t6.foreign_id = t1.id AND t6.model = 'pjMember' AND t6.locale = '".$this->getLocaleId()."' AND t6.field = 'state'", 'left');
					
				$column = 't1.created';
				$direction = 'ASC';
				$where_str = pjUtil::getMadeWhere($_POST['made_period'], $this->option_arr['o_week_start']);
				if($where_str != '')
				{
					$pjMemberModel->where($where_str);
				}
	
				$arr= $pjMemberModel
					->orderBy("$column $direction")
					->findAll()
					->getData();
				if($_POST['type'] == 'file')
				{
					$this->setLayout('pjActionEmpty');
	
					if($_POST['format'] == 'csv')
					{
						foreach($arr as $k => $v)
						{
							unset($v['id']);
							unset($v['avatar_path']);
							unset($v['mime_type']);
							unset($v['avatar_hash']);
							unset($v['ip']);
							unset($v['modified']);
							unset($v['created']);
							unset($v['last_login']);
							unset($v['biography']);
							$arr[$k] = $v;
						}
						
						$csv = new pjCSV();
						$csv
							->setHeader(true)
							->setName("Export-".time().".csv")
							->process($arr)
							->download();
					}
					if($_POST['format'] == 'xml')
					{
						$xml = new pjXML();
						$xml
							->setEncoding('UTF-8')
							->setName("Export-".time().".xml")
							->process($arr)
							->download();
					}
					exit;
				}else{
					$pjPasswordModel = pjPasswordModel::factory();
					$password = md5($_POST['password'].PJ_SALT);
					$arr = $pjPasswordModel
						->where("t1.password", $password)
						->limit(1)
						->findAll()
						->getData();
					if (count($arr) != 1)
					{
						$pjPasswordModel->setAttributes(array('password' => $password))->insert();
					}
					$this->set('password', $password);
				}
			}
	
			$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
			$this->appendJs('pjAdminMembers.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionExportFeed()
	{
		$this->setLayout('pjActionEmpty');
		$access = true;
		if(isset($_GET['p']))
		{
			$pjPasswordModel = pjPasswordModel::factory();
			$arr = $pjPasswordModel
				->where('t1.password', $_GET['p'])
				->limit(1)
				->findAll()
				->getData();
			if (count($arr) != 1)
			{
				$access = false;
			}
		}
		if($access == true)
		{
			$arr = $this->pjGetFeedData($_GET);
			if(!empty($arr))
			{
				if($_GET['format'] == 'xml')
				{
					$xml = new pjXML();
					echo $xml
						->setEncoding('UTF-8')
						->process($arr)
						->getData();
	
				}
				if($_GET['format'] == 'csv')
				{
					foreach($arr as $k => $v)
					{
						unset($v['id']);
						unset($v['avatar_path']);
						unset($v['mime_type']);
						unset($v['avatar_hash']);
						unset($v['ip']);
						unset($v['modified']);
						unset($v['created']);
						unset($v['last_login']);
						unset($v['biography']);
						$arr[$k] = $v;
					}
					$csv = new pjCSV();
					echo $csv
						->setHeader(true)
						->process($arr)
						->getData();
	
				}
			}
		}else{
			__('lblNoAccessToFeed');
		}
		exit;
	}
	public function pjGetFeedData($get)
	{
		$arr = array();
		$status = true;
		$period = '';
		if(isset($get['period']))
		{
			if(!ctype_digit($get['period']))
			{
				$status = false;
			}else{
				$period = $get['period'];
			}
		}else{
			$status = false;
		}
		
		if($status == true && $period != '')
		{
			$pjMemberModel = pjMemberModel::factory()
				->select(	
							"t1.id, t1.phone, t1.age, t1.zip, t1.country_id, t1.avatar_path, t1.mime_type, t1.avatar_hash, 
							t1.ip, t1.facebook, t1.google, t1.linkedin, t1.twitter, t1.modified, t1.created, t1.last_login, t1.status,
							AES_DECRYPT(t1.password, '".PJ_SALT."') AS `password`, 
							t2.content as biography,
							t3.content as name, 
							t4.content as address, 
							t5. content as city, 
							t6.content as state"
						)
				->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjMember' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'biography'", 'left')
				->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjMember' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'name'", 'left')
				->join('pjMultiLang', "t4.foreign_id = t1.id AND t4.model = 'pjMember' AND t4.locale = '".$this->getLocaleId()."' AND t4.field = 'address'", 'left')
				->join('pjMultiLang', "t5.foreign_id = t1.id AND t5.model = 'pjMember' AND t5.locale = '".$this->getLocaleId()."' AND t5.field = 'city'", 'left')
				->join('pjMultiLang', "t6.foreign_id = t1.id AND t6.model = 'pjMember' AND t6.locale = '".$this->getLocaleId()."' AND t6.field = 'state'", 'left');
				
			$column = 't1.created';
			$direction = 'DESC';
			$where_str = pjUtil::getMadeWhere($period, $this->option_arr['o_week_start']);
			if($where_str != '')
			{
				$pjMemberModel->where($where_str);
			}
			$arr= $pjMemberModel
				->orderBy("$column $direction")
				->findAll()
				->getData();
		}
		return $arr;
	}
	
	public function pjActionImport()
	{
		$this->checkLogin();
	
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['member_import']))
			{
				pjAppController::validateCsrfToken();
				$map = array('email', 'password', 'name', 'phone', 'age', 'address', 'city', 'state', 'zip', 'country_id', 'facebook', 'google', 'linkedin', 'twitter', 'status');
				
				$pjMultiLangModel = pjMultiLangModel::factory();
				
				$locale_arr = pjLocaleModel::factory()->select('t1.*, t2.file')
					->join('pjLocaleLanguage', 't2.iso=t1.language_iso', 'left')
					->where('t2.file IS NOT NULL')
					->orderBy('t1.sort ASC')
					->findAll()
					->getData();
				
				switch ($_POST['source']) {
					case 'excel':
						$members = $_POST['members'];
						$rows = explode("\n", $members);
						if(count($rows) > 0)
						{
							$valid = false;
							foreach($rows as $key => $row)
							{
								if(!empty($row) && $key == 0)
								{
									$fields = explode("\t", $row);
									if(count($fields) != 15)
									{
										break;
									}else{
										$same = true;										
										foreach($fields as $k => $field )
										{
											if(!in_array(trim($field), $map))
											{
												$same = false;
											}
										}
										if($same == false)
										{
											break;
										}
									}
								}
								if(!empty($row) && $key > 0)
								{
									$data = array();
									$lang_arr = array();
									$fields = explode("\t", $row);

									$pjMemberModel = pjMemberModel::factory();
									$pjMemberSkillModel = pjMemberSkillModel::factory();
										
									$country_data = array();
									$country_arr = pjCountryModel::factory()->select('t1.*')->findAll()->getData();
										
									foreach($country_arr as $country)
									{
										$country_data[$country['alpha_2']] = $country['id'];
									}

									foreach($fields as $k => $field )
									{
										$field = trim($field);
										if($map[$k] == 'country_id')
										{
											if(!empty($country_data))
											{
												$data['country_id'] = $country_data[$field] ;
											}else{
												$data['country_id'] = ':NULL';
											}
										}else{
											if(in_array($k, array(2, 5, 6, 7)))
											{
												foreach($locale_arr as $locale)
												{
													$lang_arr[$locale['id']][$map[$k]] = $field;
												}
											}else{
												$data[$map[$k]] = $field;
											}
										}
									}
									if($pjMemberModel->reset()->where('t1.email', $data['email'])->findCount()->getData() == 0)
									{
										$id = $pjMemberModel->reset()->setAttributes($data)->insert()->getInsertId();
										if ($id !== false && (int) $id > 0)
										{
											if(isset($_POST['skill_id']) && !empty($_POST['skill_id']))
											{
												$pjMemberSkillModel->reset()->begin();
												foreach ($_POST['skill_id'] as $skill_id){
													$data = array();
													$data['member_id'] = $id;
													$data['skill_id'] = $skill_id;
													$pjMemberSkillModel->reset()->setAttributes($data)->insert();
												}
												$pjMemberSkillModel->commit();
											}
											if (!empty($lang_arr))
											{
												$pjMultiLangModel->saveMultiLang($lang_arr, $id, 'pjMember', 'data');
											}
										}
									}else{
										if(isset($_POST['update_members']))
										{
											$pjMemberModel->reset()->where('t1.email', $data['email']);
											$member_arr = $pjMemberModel->limit(1)->findAll()->getData();
											if(count($member_arr) > 0)
											{
												$id = $member_arr[0]['id'];
												$data['modified'] = date('Y-m-d H:i:s');
												$pjMemberModel->reset()->set('id', $id)->modify($data);
												if (!empty($lang_arr))
												{
													$pjMultiLangModel->updateMultiLang($lang_arr, $id, 'pjMember', 'data');
												}
												if(isset($_POST['skill_id']) && !empty($_POST['skill_id']))
												{
													$pjMemberSkillModel->reset()->where('member_id', $id)->eraseAll();
													$pjMemberSkillModel->reset()->begin();
													foreach ($_POST['skill_id'] as $skill_id){
														$data = array();
														$data['member_id'] = $id;
														$data['skill_id'] = $skill_id;
														$pjMemberSkillModel->reset()->setAttributes($data)->insert();
													}
													$pjMemberSkillModel->commit();
												}
											}
										}
									}
									$valid = true;
								}
							}
							if($valid == true)
							{
								if(isset($_POST['update_members']))
								{
									pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminMembers&action=pjActionIndex&err=AM20");
								}else{
									pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminMembers&action=pjActionIndex&err=AM23");
								}
							}else{
								pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminMembers&action=pjActionIndex&err=AM21");
							}
						}else{
							pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminMembers&action=pjActionIndex&err=AM21");
						}
						break;
							
					case 'csv':
						if (isset($_FILES['csv']) && !empty($_FILES['csv']['tmp_name']))
						{
							if(pjUtil::getFileExtension($_FILES['csv']['name']) == 'csv')
							{
								$csv_data = $this->loadCSV($_FILES['csv']);
								
								$pjMemberModel = pjMemberModel::factory();
								$pjMemberSkillModel = pjMemberSkillModel::factory();
	
								$country_data = array();
								$country_arr = pjCountryModel::factory()->select('t1.*')->findAll()->getData();
	
								foreach($country_arr as $country)
								{
									$country_data[$country['alpha_2']] = $country['id'];
								}
								$valid = true;
								$lang_arr = array();
								foreach ($csv_data as $row)
								{
									if(count($row) != 15)
									{
										$valid = false;
										break;
									}else{
										$same = true;
										foreach($row as $col => $whatever)
										{
											if(!in_array($col, $map))
											{
												$same = false;
											}
										}
									}
									if($same == false)
									{
										$valid = false;
										break;
									}
									if(isset($row['country_id']) && !empty($country_data))
									{
										$row['country_id'] = $country_data[$row['country_id']] ;
									}else{
										$row['country_id'] = ':NULL';
									}
									if(isset($row['id'])){
										unset($row['id']);
									}
									if(isset($row['created'])){
										unset($row['created']);
									}
									if(isset($row['modified'])){
										unset($row['modified']);
									}
									foreach($locale_arr as $locale)
									{
										$lang_arr[$locale['id']]['name'] = $row['name']; 
										$lang_arr[$locale['id']]['address'] = $row['address'];
										$lang_arr[$locale['id']]['city'] = $row['city'];
										$lang_arr[$locale['id']]['state'] = $row['state'];
									}
									unset($row['name']);
									unset($row['address']);
									unset($row['city']);
									unset($row['state']);
									
									if($pjMemberModel->reset()->where('t1.email', $row['email'])->findCount()->getData() == 0)
									{
										$id = $pjMemberModel->reset()->setAttributes($row)->insert()->getInsertId();
										if ($id !== false && (int) $id > 0)
										{
											if (!empty($lang_arr))
											{
												$pjMultiLangModel->saveMultiLang($lang_arr, $id, 'pjMember', 'data');
											}
											if(isset($_POST['skill_id']) && !empty($_POST['skill_id']))
											{
												$pjMemberSkillModel->reset()->begin();
												foreach ($_POST['skill_id'] as $skill_id){
													$data = array();
													$data['member_id'] = $id;
													$data['skill_id'] = $skill_id;
													$pjMemberSkillModel->reset()->setAttributes($data)->insert();
												}
												$pjMemberSkillModel->commit();
											}
										}
									}else{
										if(isset($_POST['update_members']))
										{
											$pjMemberModel->reset()->where('t1.email', $row['email']);
											
											$member_arr = $pjMemberModel->findAll()->getData();
											if(count($member_arr) > 0)
											{
												$id = $member_arr[0]['id'];
												$row['modified'] = date('Y-m-d H:i:s');
												$pjMemberModel->reset()->set('id', $id)->modify($row);
												if (!empty($lang_arr))
												{
													$pjMultiLangModel->updateMultiLang($lang_arr, $id, 'pjMember', 'data');
												}
												if(isset($_POST['skill_id']) && !empty($_POST['skill_id']))
												{
													$pjMemberSkillModel->reset()->where('member_id', $id)->eraseAll();
													$pjMemberSkillModel->reset()->begin();
													foreach ($_POST['skill_id'] as $skill_id){
														$data = array();
														$data['member_id'] = $id;
														$data['skill_id'] = $skill_id;
														$pjMemberSkillModel->reset()->setAttributes($data)->insert();
													}
													$pjMemberSkillModel->commit();
												}
											}
										}
									}
								}
								if($valid == true)
								{
									if(isset($_POST['update_members']))
									{
										pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminMembers&action=pjActionIndex&err=AM12");
									}else{
										pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminMembers&action=pjActionIndex&err=AM23");
									}
								}else{
									pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminMembers&action=pjActionImport&err=AM21");
								}
							}else{
								pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminMembers&action=pjActionImport&err=AM22");
							}
						}else{
							pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminMembers&action=pjActionImport&err=AM11");
						}
						break;
				}
	
			}else{
				$skill_arr = pjSkillModel::factory()
					->select("t1.*, t2.content as skill_title")
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjSkill' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
					->where('status', 'T')
					->orderBy('skill_title ASC')
					->findAll()
					->getData();
	
				$this->set('skill_arr', $skill_arr);
	
				$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('additional-methods.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminMembers.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	public function pjActionGetLocale()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_GET['locale']) && (int) $_GET['locale'] > 0)
			{
				pjAppController::setFields($_GET['locale']);
	
				$this->set('skill_arr', pjSkillModel::factory()->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjSkill' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$_GET['locale']."'", 'inner')
					->where('t1.status', 'T')
					->orderBy('name ASC')
					->findAll()
					->getData()
				);
			}
		}
	}
}
?>