<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminMembers extends pjAdmin
{
	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())
		{
			if (isset($_POST['member_create']))
			{
				$pjMemberModel = pjMemberModel::factory();
				
				$data = array();
				if (isset($_POST['membership_expire']) && !empty($_POST['membership_expire']))
				{
					$data['membership_expire'] = pjUtil::formatDate($_POST['membership_expire'], $this->option_arr['o_date_format']);
				}
				if (isset($_POST['birthday']) && !empty($_POST['birthday']))
				{
					$data['birthday'] = pjUtil::formatDate($_POST['birthday'], $this->option_arr['o_date_format']);
				}
				unset($_POST['membership_expire']);
				unset($_POST['birthday']);
				
				$data['ip'] = $_SERVER['REMOTE_ADDR'];
				
				$data = array_merge($_POST, $data);
				
				$id = $pjMemberModel->setAttributes($data)->insert()->getInsertId();
				
				if ($id !== false && (int) $id > 0)
				{
					$err = 'AM03';
				} else {
					$err = 'AM04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminMembers&action=pjActionIndex&err=$err");
			} else {
				
				$group_arr = pjGroupModel::factory()->where('status', 'T')->orderBy('group_title ASC')->findAll()->getData();
				
				$country_arr = pjCountryModel::factory()->select('t1.*, 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')
						->where('status', 'T')->orderBy('country_title ASC')->findAll()->getData();
				
				$this->set('group_arr', $group_arr);
				$this->set('country_arr', $country_arr);
				
				$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
			
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('additional-methods.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminMembers.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionImport()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			if (isset($_POST['member_import']))
			{
				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();
						
						$country_arr = pjCountryModel::factory()->select('t1.*')->findAll()->getDataPair('alpha_2', 'id');
						
						$err = 'AM09';
						$pjMemberModel->begin();
						foreach ($csv_data as $row)
						{
							if(!isset($row['email']) || !isset($row['first_name']))
							{
								pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminMembers&action=pjActionImport&err=AM14");
							}
							if($pjMemberModel->reset()->where('t1.email', $row['email'])->findCount()->getData() == 0)
							{
								if(isset($row['country_id']) && !empty($country_arr))
								{
									$row['country_id'] = $country_arr[$row['country_id']];
								}else{
									$row['country_id'] = ':NULL';
								}
								if(isset($row['created'])){
									unset($row['created']);
								}
								if(isset($row['modified'])){
									unset($row['modified']);
								}
								if(!empty($_POST['group_id']))
								{
									$row['group_id'] = $_POST['group_id'];
								}
								$pjMemberModel->reset()->setAttributes($row)->insert();
							}else{
								$err = 'AM13';
							}
						}
						$pjMemberModel->commit();
						
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminMembers&action=pjActionIndex&err=$err");
						
					}else{
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminMembers&action=pjActionImport&err=AM10");
					}
				}else{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminMembers&action=pjActionImport&err=AM11");
				}
			}else{
				$group_arr = pjGroupModel::factory()->where('status', 'T')->orderBy('group_title ASC')->findAll()->getData();
				
				$this->set('group_arr', $group_arr);
				
				$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . '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 pjActionDeleteMember()
	{
		$this->setAjax(true);
		
		if ($this->isXHR())
		{
			$response = array();
			if ($this->isAdmin())
			{
				$pjMemberModel = pjMemberModel::factory();
				$uuid_arr = $pjMemberModel->where('id', $_GET['id'])->findAll()->getDataPair(NULL, 'uuid');
				if ($pjMemberModel->reset()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
				{
					if(!empty($uiid_arr))
					{
						pjInvoiceModel::factory()->whereIn('order_id', $uuid_arr)->eraseAll();
					}
					$response['code'] = 200;
				} else {
					$response['code'] = 100;
				}
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteMemberBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if ($this->isAdmin() || $this->isEditor())
			{
				if (isset($_POST['record']) && count($_POST['record']) > 0)
				{
					$pjMemberModel = pjMemberModel::factory();
					$uuid_arr = $pjMemberModel->whereIn('id', $_POST['record'])->findAll()->getDataPair(NULL, 'uuid');
					$pjMemberModel->reset()->whereIn('id', $_POST['record'])->eraseAll();
					if(!empty($uiid_arr))
					{
						pjInvoiceModel::factory()->whereIn('order_id', $uuid_arr)->eraseAll();
					}
				}
			}
		}
		exit;
	}
	
	public function pjActionExportMember()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjMemberModel::factory()->select("t1.first_name, t1.last_name, t1.email, AES_DECRYPT(t1.password, '".PJ_SALT."') as password, t1.phone, t1.website, t1.gender, t1.age, t1.birthday, t1.address, t1.city, t1.state, t1.country_id, t1.zip, t1.company_name, t1.ip, t1.created, t1.status")
					->whereIn('id', $_POST['record'])->findAll()->getData();
			
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Members-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionGetMember()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjMemberModel = pjMemberModel::factory();
			$pjMemberModel->join('pjGroup', 't1.group_id = t2.id', 'left outer');
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = $pjMemberModel->escapeStr($_GET['q']);
				$q = str_replace(array('%', '_'), array('\%', '\_'), trim($q));
				$pjMemberModel->where("(t1.first_name LIKE '%$q%' OR t1.last_name LIKE '%$q%' OR t1.email LIKE '%$q%')");
			}
			if (isset($_GET['first_name']) && !empty($_GET['first_name']))
			{
				$fname = $pjMemberModel->escapeStr($_GET['first_name']);
				$fname = str_replace(array('%', '_'), array('\%', '\_'), trim($fname));
				$pjMemberModel->where("(t1.first_name LIKE '%$fname%')");
			}
			if (isset($_GET['last_name']) && !empty($_GET['last_name']))
			{
				$lname = $pjMemberModel->escapeStr($_GET['last_name']);
				$lname = str_replace(array('%', '_'), array('\%', '\_'), trim($lname));
				$pjMemberModel->where("(t1.last_name LIKE '%$lname%')");
			}
			if (isset($_GET['email']) && !empty($_GET['email']))
			{
				$email = $pjMemberModel->escapeStr($_GET['email']);
				$email = str_replace(array('%', '_'), array('\%', '\_'), trim($email));
				$pjMemberModel->where("(t1.email LIKE '%$email%')");
			}
			if (isset($_GET['last_login']) && !empty($_GET['last_login']))
			{
				if($_GET['last_login'] == 'today')
				{
					$login_filter = date('Y-m-d');
					$pjMemberModel->where("(t1.last_login LIKE '%$login_filter%')");
				}else{
					switch ($_GET['last_login']) {
						case '7_days':
							$login_filter = date('Y-m-d H:i:s', strtotime('-7 days'));
						break;
						case '30_days':
							$login_filter = date('Y-m-d H:i:s', strtotime('-30 days'));;
						break;
						case '3_months':
						 	$login_filter = date('Y-m-d H:i:s', strtotime('-3 months'));;
						break;
					}
					$pjMemberModel->where("(t1.last_login >= '$login_filter')");
				}
			}
			if (isset($_GET['country_id']) && !empty($_GET['country_id']))
			{
				$pjMemberModel->where("t1.country_id", $_GET['country_id']);
			}
			
			if (isset($_GET['group_id']) && !empty($_GET['group_id']))
			{
				$pjMemberModel->where("t1.group_id", $_GET['group_id']);
			}

			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('T', 'F')))
			{
				$pjMemberModel->where('t1.status', $_GET['status']);
			}
			if (isset($_GET['gender']) && !empty($_GET['gender']) && in_array($_GET['gender'], array('F', 'M')))
			{
				$pjMemberModel->where('t1.gender', $_GET['gender']);
			}
			if (isset($_GET['age_from']) && $_GET['age_from'] != '' && isset($_GET['age_to']) && $_GET['age_to'] != '')
			{
				$pjMemberModel->where('t1.age >=', $_GET['age_from']);
				$pjMemberModel->where('t1.age <=', $_GET['age_to']);
			} else {
				if (isset($_GET['age_from']) && $_GET['age_from'] != '')
				{
					$pjMemberModel->where('t1.age >=', $_GET['age_from']);
				} else if (isset($_GET['age_to']) && $_GET['age_to'] != '') {
					$pjMemberModel->where('t1.age <=', $_GET['age_to']);
				}
			}
				
			$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 = $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, CONCAT_WS(' ', t1.first_name, t1.last_name) AS `name`, t1.email,
				t1.membership_expire, t1.created, t1.status, t2.group_title")
				->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())
		{
			$group_arr = pjGroupModel::factory()->where('status', 'T')->orderBy('group_title ASC')->findAll()->getData();
			$country_arr = pjCountryModel::factory()->select('t1.*, 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')
					->where('status', 'T')->orderBy('country_title ASC')->findAll()->getData();
			
			$this->set('group_arr', $group_arr);
			$this->set('country_arr', $country_arr);
			
			$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'chosen/');
			$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
			
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminMembers.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveMember()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if($_POST['column'] == 'first_name')
			{
				if($_POST['value'] != '')
				{
					pjMemberModel::factory()->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
				}
			}else{
				pjMemberModel::factory()->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
			}
		}
		exit;
	}
	
	public function pjActionStatusMember()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjMemberModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array(
					'status' => ":IF(`status`='F','T','F')"
				));
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			$pjMemberModel = pjMemberModel::factory();
			
			$pjMemberModel = pjMemberModel::factory();
			if (isset($_REQUEST['id']) && (int) $_REQUEST['id'] > 0)
			{
				$pjMemberModel->where('t1.id', $_REQUEST['id']);
			} elseif (isset($_GET['uuid']) && !empty($_GET['uuid'])) {
				$pjMemberModel->where('t1.uuid', $_GET['uuid']);
			}
			$arr = $pjMemberModel
				->limit(1)
				->findAll()
				->getData();
			
			if (empty($arr))
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminBookings&action=pjActionIndex&err=ABK08");
			}
			$arr = $arr[0];
				
			if (isset($_POST['member_update']))
			{
				$data = array();
				if (isset($_POST['birthday']) && !empty($_POST['birthday']))
				{
					$data['birthday'] = pjUtil::formatDate($_POST['birthday'], $this->option_arr['o_date_format']);
				}
				unset($_POST['birthday']);
				$data['ip'] = $_SERVER['REMOTE_ADDR'];
				
				$data['modified'] = date('Y-m-d H:i:s');
				if (isset($_POST['membership_expire']) && !empty($_POST['membership_expire']))
				{
					$data['membership_expire'] = pjUtil::formatDate($_POST['membership_expire'], $this->option_arr['o_date_format']);
				} else {
					$data['membership_expire'] = ':NULL';
				}
				
				$data = array_merge($_POST, $data);
				
				$pjMemberModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll($data);
								
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminMembers&action=pjActionIndex&err=AM01");
				
			} else {
				$this->set('arr', $arr);
				
				$group = pjGroupModel::factory()->find($arr['group_id'])->getData();
				
				$group_arr = pjGroupModel::factory()->where('status', 'T')->orderBy('group_title ASC')->findAll()->getData();
				
				$country_arr = pjCountryModel::factory()->select('t1.*, 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')
						->where('status', 'T')->orderBy('country_title ASC')->findAll()->getData();
				
				$pjInvoiceModel = pjInvoiceModel::factory();
				$total_invoices = $pjInvoiceModel->where('order_id', $arr['uuid'])->findCount()->getData();
				$invoice_arr = $pjInvoiceModel->reset()->where('order_id', $arr['uuid'])->orderBy('`created` DESC')->limit(1)->findAll()->getData();
				$last_invoice = count($invoice_arr) == 1 ? $invoice_arr[0] : array();
				
				$this->set('group_arr', $group_arr);
				$this->set('group', $group);
				$this->set('total_invoices', $total_invoices);
				$this->set('last_invoice', $last_invoice);
				$this->set('country_arr', $country_arr);
				
				$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
							
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
				$this->appendJs('additional-methods.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminMembers.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
}
?>