<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjFront extends pjAppController
{
	public $defaultCaptcha = 'StivaSoftCaptcha';
	
	public $defaultLocale = 'front_locale_id';
	
	public $defaultMember = 'front_default_member';
	
	public $defaultGroupId = 'front_default_group_id';
	
	public $defaultGoogleToken = 'front_default_google_token';
	
	public function __construct()
	{
		$this->setLayout('pjActionFront');
		self::allowCORS();
	}
	public function isXHR()
	{
		return parent::isXHR() || isset($_SERVER['HTTP_ORIGIN']);
	}
	
	static protected function allowCORS()
	{
		$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
		header("Access-Control-Allow-Origin: $origin");
		header("Access-Control-Allow-Credentials: true");
		header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
		header("Access-Control-Allow-Headers: Origin, X-Requested-With");
	}
	public function afterFilter()
	{
		
	}
	
	public function beforeFilter()
	{
		$OptionModel = pjOptionModel::factory();
		$this->option_arr = $OptionModel->getPairs($this->getForeignId());
		$this->set('option_arr', $this->option_arr);
		$this->setTime();

		if (!isset($_SESSION[$this->defaultLocale]))
		{
			$locale_arr = pjLocaleModel::factory()->where('is_default', 1)->limit(1)->findAll()->getData();
			if (count($locale_arr) === 1)
			{
				$this->setLocaleId($locale_arr[0]['id']);
			}
		}
		$this->loadSetFields();
	}
	
	public function beforeRender()
	{
		if (isset($_GET['iframe']))
		{
			$this->setLayout('pjActionIframe');
		}
	}
	
	public function pjActionSetLocale()
	{
		$this->setLocaleId(@$_GET['locale']);
		pjUtil::redirect($_SERVER['HTTP_REFERER']);
	}
	
	public function pjActionCaptcha()
	{
		$this->setAjax(true);
		header("Cache-Control: max-age=3600, private");
		$Captcha = new pjCaptcha(PJ_WEB_PATH.'obj/Anorexia.ttf', $this->defaultCaptcha, 6);
		$Captcha->setImage(PJ_IMG_PATH.'button.png')->init(isset($_GET['rand']) ? $_GET['rand'] : null);
		exit;
	}

	public function pjActionCheckCaptcha()
	{
		$this->setAjax(true);
				
		if (!isset($_GET['captcha']) || empty($_GET['captcha']) || strtoupper($_GET['captcha']) != $_SESSION[$this->defaultCaptcha]){
			echo 101;
		}else{
			echo 100;
		}
	}
	
	public function pjActionCheckEmail()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (!isset($_GET['email']) || empty($_GET['email']))
			{
				echo 101;
				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 ? 100 : 101;
		}
		exit;
	}
	
	public function pjActionLoadCss()
	{
		header("Content-type: text/css");
		$arr = array(
			array('file' => 'front.css', 'path' => PJ_CSS_PATH),
		);
		foreach ($arr as $item)
		{
			$css_content = file_get_contents($item['path'] . $item['file']);
			echo str_replace(array('../img/'), array(PJ_IMG_PATH), $css_content) . "\n";
		}
		exit;
	}
	
	public function pjActionRegisterJs()
	{
		header("Content-type: text/javascript");
		$arr = array(
			array('file' => 'jabb-0.4.3.js', 'path' => PJ_LIBS_PATH . 'jabb/'),
			array('file' => 'pjRegister.js', 'path' => PJ_JS_PATH)
		);
		foreach ($arr as $item)
		{
			$js_content = file_get_contents($item['path'] . $item['file']);
			echo $js_content . "\n";
		}
		exit;
	}
	
	public function pjActionRegister()
	{
		
		$this->setLayout('pjActionFrontJS');
		
	}
	public function pjActionRegisterForm()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			require_once PJ_LIBS_PATH . 'google/Google_Client.php';
			require_once PJ_LIBS_PATH . 'google/contrib/Google_Oauth2Service.php';
				
			$pjGroupModel = pjGroupModel::factory();
		
			$group_arr = $pjGroupModel->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();
			
			if(isset($_GET['group_id']))
			{
				$arr = $pjGroupModel->reset()->find($_GET['group_id'])->getData();
				$this->set('arr', $arr);
			}
			
			$authUrl = '#';
			$loginUrl = '#';
			
			$clientId = $this->option_arr['o_google_client_id'];
			$clientSecret = $this->option_arr['o_google_client_secret'];
			$redirectURL = PJ_INSTALL_URL . 'index.php?controller=pjFront&action=pjActionGoogleLogin';
				
			$gClient = new Google_Client();
			
			$gClient->setApplicationName('Login to Member Login');
			$gClient->setClientId($clientId);
			$gClient->setClientSecret($clientSecret);
			$gClient->setRedirectUri($redirectURL);
				
			$google_oauthV2 = new Google_Oauth2Service($gClient);
			
			$authUrl = $gClient->createAuthUrl();
			
			$appId = $this->option_arr['o_facebook_app_id'];
			$appSecret = $this->option_arr['o_facebook_app_secret'];
			$redirectURL = PJ_INSTALL_URL . 'index.php?controller=pjFront&action=pjActionFacebookLogin';
			$fbPermissions = 'email'; 
			
			$facebook = new pjFacebook(
			    $appId,
			    $appSecret,
			    $redirectURL
		    );
			
			$user_profile = $facebook->getUser();
			if (!$user_profile)
			{
			    $loginUrl = $facebook->getLoginUrl();
			}
			
			$this->set('group_arr', $group_arr);
			$this->set('country_arr', $country_arr);
			
			$this->set('authUrl', $authUrl);
			$this->set('loginUrl', $loginUrl);
		}
	}
	public function pjActionGetFee()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$arr = pjGroupModel::factory()->find($_GET['id'])->getData();
			
			if(!empty($arr))
			{
				if(!empty($arr['registration_fee']) && $arr['registration_fee'] > 0)
				{
					$arr['registration_fee'] = pjUtil::formatCurrencySign($arr['registration_fee'], $this->option_arr['o_currency']);
				}else{
					$arr['registration_fee'] = '';
				}
				$period_per = __('period_per', true);
				if(!empty($arr['subscription_fee']) && $arr['subscription_fee'] > 0)
				{
					$arr['subscription_fee'] = pjUtil::formatCurrencySign($arr['subscription_fee'], $this->option_arr['o_currency']) . ' ' . $period_per[$arr['subscription_period']];
				}else{
					$arr['subscription_fee'] = '';
				}
			}
			
			pjAppController::jsonResponse($arr);
		}
		exit;
	}
	public function pjActionRegisterSave()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			// Check captcha
			if (
				!pjValidation::pjActionNotEmpty($_SESSION[$this->defaultCaptcha]) ||
				!pjValidation::pjActionNotEmpty($_POST['captcha']) ||
				!pjCaptcha::validate($_POST['captcha'], $_SESSION[$this->defaultCaptcha])
			) {
				$this->jsonResponse(array('code' => 101));
			}

			$pjMemberModel = pjMemberModel::factory();
			$data = array();
			$birthday = '';

			$json = array();
			$json['code'] = 100;
			if (!empty($_POST['day']) && !empty($_POST['month']) && !empty($_POST['year']))
			{
				$data['birthday'] = $_POST['year'] . '-' . $_POST['month'] . '-' . $_POST['day'];
				$birthday = pjUtil::formatDate($data['birthday'], 'Y-m-d', $this->option_arr['o_date_format']);
			}
			$data['ip'] = $_SERVER['REMOTE_ADDR'];
			$data['uuid'] = pjUtil::uuid();
			$data['status'] = 'F';
			
			$group_arr = pjGroupModel::factory()->find($_POST['group_id'])->getData();
			if(!empty($group_arr))
			{
				switch ($group_arr['subscription_period']) {
					case 'week':
						$data['membership_expire'] = date('Y-m-d', time() + 7 * 86400);
						break;
							
					case 'month':
						$data['membership_expire'] = date('Y-m-d', time() + 30 * 86400);
						break;
					case 'year':
						$data['membership_expire'] = date('Y-m-d', time() + 365 * 86400);
						break;
				}
			}
			
			$data = array_merge($_POST, $data);

			// Check for required fields
			if (!$pjMemberModel->beforeValidate($this->option_arr, 'register')->validates($data)) {
				$this->jsonResponse(array('code' => 101));
			}

			// Check for existing member
			if ($pjMemberModel->reset()->where('t1.email', $data['email'])->findCount()->getData()) {
				$this->jsonResponse(array('code' => 102));
			}

			// Save member
			$id = $pjMemberModel->reset()->setAttributes($data)->insert()->getInsertId();
			if ($id !== false && (int) $id > 0)
			{
				$amount = floatval($group_arr['registration_fee']) + floatval($group_arr['subscription_fee']);
				if($amount > 0)
				{
					$this->pjActionGenerateInvoice($id);
				}
				
				$this->pjAdminNotification($id, $_POST['group_id']);
				if($this->option_arr['o_registration_confirmation'] == 'manual')
				{
					$this->pjRegistrationCreated($id, $_POST['group_id']);
				}else if($this->option_arr['o_registration_confirmation'] == 'confirm'){
					$this->pjRegistrationConfirmation($id, $_POST['group_id']);
					$json['code'] = 100;
					$json['id'] = $id;
				}else if($this->option_arr['o_registration_confirmation'] == 'payment'){
					if($amount <= 0)
					{
						$json['code'] = 100;
						$pjMemberModel->reset()->where('id', $id)->limit(1)->modifyAll(array('status' => 'T'));
					}else{
						$json['code'] = 200;
						$json['id'] = $id;
					}
				}

				$_SESSION[$this->defaultCaptcha] = null;
				unset($_SESSION[$this->defaultCaptcha]);
			} else {
				$json['code'] = 101;
			}
			pjAppController::jsonResponse($json);
		}
		exit;
	}
	public function pjActionSetGroup()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$json = array();
			if(isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$json['code'] = 200;
				$_SESSION[$this->defaultGroupId] = (int) $_GET['id'];
				$json['group_id'] = $_SESSION[$this->defaultGroupId];
			}else{
				$json['code'] = 100;
			}
			pjAppController::jsonResponse($json);
		}
		exit;
	}
	public function pjActionGoogleLogin()
	{
		$this->setLayout('pjActionFront'); 
		
		$group_id = NULL;
		if(isset($_SESSION[$this->defaultGroupId]) && (int) $_SESSION[$this->defaultGroupId] > 0)
		{
			$group_id = (int) $_SESSION[$this->defaultGroupId];
			unset($_SESSION[$this->defaultGroupId]);
		}
		if(isset($_GET['id']) && (int) $_GET['id'] > 0 && isset($_GET['group_id']) && (int) $_GET['group_id'] > 0)
		{
			$member_arr = pjMemberModel::factory()->find($_GET['id'])->getData();
			$group_arr = pjGroupModel::factory()->find($member_arr['group_id'])->getData();
				
			$amount = number_format(floatval($group_arr['registration_fee']) + floatval($group_arr['subscription_fee']), 2, '.', '');
			$subscription_fee = number_format(floatval($group_arr['subscription_fee']), 2, '.', '');
			$item_name = $group_arr['group_title'] . ' ' . pjUtil::formatCurrencySign(floatval($group_arr['registration_fee']), $this->option_arr['o_currency']) . ' ' . __('front_label_registration_fee', true) . ' + ' . pjUtil::formatCurrencySign(floatval($group_arr['subscription_fee']), $this->option_arr['o_currency']) . ' ' . __('front_label_subscription_fee', true);
			$t3 = 'M';
			if ($group_arr['subscription_period'] == 'week')
			{
				$t3 = 'W';
			} else if($group_arr['subscription_period'] == 'year') {
				$t3 = 'Y';
			}
			$this->set('params', array(
					'name' => 'ml_memberlogin_paypal_form',
					'id' => 'ml_memberlogin_paypal_form',
					'business' => $this->option_arr['o_paypal_address'],
					'item_name' => $item_name,
					'custom' => $member_arr['id'],
					'currency_code' => $this->option_arr['o_currency'],
					'return' => $this->option_arr['o_thankyou_page'],
					'notify_url' => PJ_INSTALL_URL . 'index.php?controller=pjFront&action=pjActionConfirmPaypal',
					'target' => '_self',
		
					'amount' => $amount,
						
					'a1_price' => $amount,
					'p1_duration' => 1,
					't1_duration_unit' => $t3,
						
					'a3_price' => $subscription_fee,
					'p3_duration' => 1,
					't3_duration_unit' => $t3,
		
					'recurring_payments' => 1,
					'reattempt_on_failure' => 0
			));
		}else{
			require_once PJ_LIBS_PATH . 'google/Google_Client.php';
			require_once PJ_LIBS_PATH . 'google/contrib/Google_Oauth2Service.php';
				
			$clientId = $this->option_arr['o_google_client_id'];
			$clientSecret = $this->option_arr['o_google_client_secret'];
			$redirectURL = PJ_INSTALL_URL . 'index.php?controller=pjFront&action=pjActionGoogleLogin';
			
			$gClient = new Google_Client();
			$gClient->setApplicationName('Login to Member Login');
			$gClient->setClientId($clientId);
			$gClient->setClientSecret($clientSecret);
			$gClient->setRedirectUri($redirectURL);
			
			$google_oauthV2 = new Google_Oauth2Service($gClient);
				
			if(isset($_GET['code'])){
			
				$gClient->authenticate($_GET['code']);
				$_SESSION[$this->defaultGoogleToken] = $gClient->getAccessToken();
				header('Location: ' . filter_var($redirectURL, FILTER_SANITIZE_URL));
			}
			if (isset($_SESSION[$this->defaultGoogleToken])) {
				$gClient->setAccessToken($_SESSION[$this->defaultGoogleToken]);
			}
			if ($gClient->getAccessToken())
			{
				$gpUserProfile = $google_oauthV2->userinfo->get();
				
				$pjMemberModel = pjMemberModel::factory();
			
				$member = $pjMemberModel->where('email', $gpUserProfile['email'])->limit(1)->findAll()->getData();
			
				if(count($member) == 1 && !isset($_GET['log_err']))
				{
					$member = $member[0];
					unset($member['password']);
						
					if ($member['status'] == 'F')
					{
						if (!empty($this->option_arr['o_thankyou_page']))
						{
							pjUtil::redirect($this->option_arr['o_thankyou_page']);
						}
						header('Location: ' . filter_var($redirectURL . '&log_err=103', FILTER_SANITIZE_URL));
					}else{
						$group_arr = pjGroupModel::factory()->find($member['group_id'])->getData();
						$amount = floatval($group_arr['registration_fee']) + floatval($group_arr['subscription_fee']);
			
						$login = false;
						if($amount > 0)
						{
							if (empty($member['membership_expire']) || strtotime($member['membership_expire']) <= strtotime(date("Y-m-d")))
							{
								header('Location: ' . filter_var($redirectURL . '&log_err=104', FILTER_SANITIZE_URL));
							}else{
								$login = true;
							}
						}else{
							$login = true;
						}
						if($login == true)
						{
							$last_login = date("Y-m-d H:i:s");
							$_SESSION[$this->defaultMember] = $member;
			
							$data = array();
							$data['last_login'] = $last_login;
							$pjMemberModel->reset()->setAttributes(array('id' => $member['id']))->modify($data);
			
							if (!empty($group_arr))
							{
								if($group_arr['home_url'] != '')
								{
									header('Location: ' . filter_var($group_arr['home_url'], FILTER_SANITIZE_URL));
								}else{
									header('Location: ' . filter_var($redirectURL . '&log_err=100', FILTER_SANITIZE_URL));
								}
							}
						}
					}
				}else{
					if($group_id != NULL)
					{
						$data = array();
						$data['group_id'] = $group_id;
						$data['uuid'] = pjUtil::uuid();
						$data['first_name'] = $gpUserProfile['given_name'];
						$data['last_name'] = $gpUserProfile['family_name'];
						$data['email'] = $gpUserProfile['email'];
						$data['gender'] = $gpUserProfile['gender'] == 'male' ? 'M' : 'F';
						$data['password'] = 'pass';
						$data['status'] = 'F';
			
						$group_arr = pjGroupModel::factory()->find($group_id)->getData();
						if(!empty($group_arr))
						{
							switch ($group_arr['subscription_period']) {
								case 'week':
									$data['membership_expire'] = date('Y-m-d', time() + 7 * 86400);
									break;
										
								case 'month':
									$data['membership_expire'] = date('Y-m-d', time() + 30 * 86400);
									break;
								case 'year':
									$data['membership_expire'] = date('Y-m-d', time() + 365 * 86400);
									break;
							}
						}
						$id = $pjMemberModel->reset()->setAttributes($data)->insert()->getInsertId();
							
						if ($id !== false && (int) $id > 0)
						{
							$amount = floatval($group_arr['registration_fee']) + floatval($group_arr['subscription_fee']);

							if($amount > 0)
							{
								$this->pjActionGenerateInvoice($id);
							}
							
							$this->pjAdminNotification($id, $group_id);
							if($this->option_arr['o_registration_confirmation'] == 'manual')
							{
								$this->pjRegistrationCreated($id, $group_id);
								header('Location: ' . filter_var($redirectURL . '&reg_err=100', FILTER_SANITIZE_URL));
							}else if($this->option_arr['o_registration_confirmation'] == 'confirm'){
								$this->pjRegistrationConfirmation($id, $group_id);
								header('Location: ' . filter_var($redirectURL . '&reg_err=100', FILTER_SANITIZE_URL));
							}else if($this->option_arr['o_registration_confirmation'] == 'payment'){
								if($amount <= 0)
								{
									$pjMemberModel->reset()->where('id', $id)->limit(1)->modifyAll(array('status' => 'T'));
									header('Location: ' . filter_var($redirectURL . '&reg_err=100', FILTER_SANITIZE_URL));
								}else{
									header('Location: ' . filter_var($redirectURL . '&reg_err=102&group_id=' . $group_id . '&id=' . $id, FILTER_SANITIZE_URL));
								}
							}
						} else {
							header('Location: ' . filter_var($redirectURL . '&reg_err=101', FILTER_SANITIZE_URL));
						}
					}else if(!isset($_GET['log_err'])){
						header('Location: ' . filter_var($redirectURL . '&log_err=105', FILTER_SANITIZE_URL));
					}
				}
			}
		}
		$this->appendCss('front.css');
	}
	public function pjActionFacebookLogin()
	{
		$this->setLayout('pjActionFront');
	
		if(isset($_GET['id']) && (int) $_GET['id'] > 0 && isset($_GET['group_id']) && (int) $_GET['group_id'] > 0)
		{
			$member_arr = pjMemberModel::factory()->find($_GET['id'])->getData();
			$group_arr = pjGroupModel::factory()->find($member_arr['group_id'])->getData();
			
			$amount = number_format(floatval($group_arr['registration_fee']) + floatval($group_arr['subscription_fee']), 2, '.', '');
			$subscription_fee = number_format(floatval($group_arr['subscription_fee']), 2, '.', '');
			$item_name = $group_arr['group_title'] . ' ' . pjUtil::formatCurrencySign(floatval($group_arr['registration_fee']), $this->option_arr['o_currency']) . ' ' . __('front_label_registration_fee', true) . ' + ' . pjUtil::formatCurrencySign(floatval($group_arr['subscription_fee']), $this->option_arr['o_currency']) . ' ' . __('front_label_subscription_fee', true);
			$t3 = 'M';
			if ($group_arr['subscription_period'] == 'week')
			{
				$t3 = 'W';
			} else if($group_arr['subscription_period'] == 'year') {
				$t3 = 'Y';
			}
			$this->set('params', array(
					'name' => 'ml_memberlogin_paypal_form',
					'id' => 'ml_memberlogin_paypal_form',
					'business' => $this->option_arr['o_paypal_address'],
					'item_name' => $item_name,
					'custom' => $member_arr['id'],
					'currency_code' => $this->option_arr['o_currency'],
					'return' => $this->option_arr['o_thankyou_page'],
					'notify_url' => PJ_INSTALL_URL . 'index.php?controller=pjFront&action=pjActionConfirmPaypal',
					'target' => '_self',
						
					'amount' => $amount,
			
					'a1_price' => $amount,
					'p1_duration' => 1,
					't1_duration_unit' => $t3,
			
					'a3_price' => $subscription_fee,
					'p3_duration' => 1,
					't3_duration_unit' => $t3,
						
					'recurring_payments' => 1,
					'reattempt_on_failure' => 0
			));
		}else{
			$group_id = NULL;
			if(isset($_SESSION[$this->defaultGroupId]) && (int) $_SESSION[$this->defaultGroupId] > 0)
			{
				$group_id = $_SESSION[$this->defaultGroupId];
				unset($_SESSION[$this->defaultGroupId]);
			}
			
			$appId = $this->option_arr['o_facebook_app_id'];
			$appSecret = $this->option_arr['o_facebook_app_secret'];
			$redirectURL = PJ_INSTALL_URL . 'index.php?controller=pjFront&action=pjActionFacebookLogin';
			$fbPermissions = 'email';
			
			$facebook = new pjFacebook($appId, $appSecret, $redirectURL);
			$fbUser = false;
			try {
			    $facebook->requestAccessToken($_GET['code']);
			    $facebook->requestValidateToken();
			    $fbUser = $facebook->requestUser();
			} catch (Exception $e) {
			    
			}
			if($fbUser)
			{
				$pjMemberModel = pjMemberModel::factory();
					
				$member = $pjMemberModel->where('email', $fbUser['email'])->limit(1)->findAll()->getData();
					
				if(count($member) == 1 && !isset($_GET['log_err']))
				{
					$member = $member[0];
					unset($member['password']);
						
					if ($member['status'] == 'F')
					{
						header('Location: ' . filter_var($redirectURL . '&log_err=103', FILTER_SANITIZE_URL));
					}else{
						$group_arr = pjGroupModel::factory()->find($member['group_id'])->getData();
						$amount = floatval($group_arr['registration_fee']) + floatval($group_arr['subscription_fee']);
							
						$login = false;
						if($amount > 0)
						{
							if (empty($member['membership_expire']) || strtotime($member['membership_expire']) <= strtotime(date("Y-m-d")))
							{
								header('Location: ' . filter_var($redirectURL . '&log_err=104', FILTER_SANITIZE_URL));
							}else{
								$login = true;
							}
						}else{
							$login = true;
						}
						if($login == true)
						{
							$last_login = date("Y-m-d H:i:s");
							$_SESSION[$this->defaultMember] = $member;
								
							$data = array();
							$data['last_login'] = $last_login;
							$pjMemberModel->reset()->setAttributes(array('id' => $member['id']))->modify($data);
							if (!empty($group_arr))
							{
								if($group_arr['home_url'] != '')
								{
									header('Location: ' . filter_var($group_arr['home_url'], FILTER_SANITIZE_URL));
								}else{
									header('Location: ' . filter_var($redirectURL . '&log_err=100', FILTER_SANITIZE_URL));
								}
							}
						}
					}
				}else{
					if($group_id != NULL)
					{
						$data = array();
						$data['group_id'] = $group_id;
						$data['uuid'] = pjUtil::uuid();
						$data['first_name'] = $fbUser['first_name'];
						$data['last_name'] = $fbUser['last_name'];
						$data['email'] = $fbUser['email'];
						$data['gender'] = $fbUser['gender'] == 'male' ? 'M' : 'F';
						$data['password'] = 'pass';
						$data['status'] = 'F';
						$group_arr = pjGroupModel::factory()->find($group_id)->getData();
						if(!empty($group_arr))
						{
							switch ($group_arr['subscription_period']) {
								case 'week':
									$data['membership_expire'] = date('Y-m-d', time() + 7 * 86400);
									break;
										
								case 'month':
									$data['membership_expire'] = date('Y-m-d', time() + 30 * 86400);
									break;
								case 'year':
									$data['membership_expire'] = date('Y-m-d', time() + 365 * 86400);
									break;
							}
						}
						$id = $pjMemberModel->reset()->setAttributes($data)->insert()->getInsertId();
							
						if ($id !== false && (int) $id > 0)
						{
							$amount = floatval($group_arr['registration_fee']) + floatval($group_arr['subscription_fee']);
				
							if($amount > 0)
							{
								$this->pjActionGenerateInvoice($id);
							}
							
							$this->pjAdminNotification($id, $group_id);
							if($this->option_arr['o_registration_confirmation'] == 'manual')
							{
								$this->pjRegistrationCreated($id, $group_id);
								header('Location: ' . filter_var($redirectURL . '&reg_err=100', FILTER_SANITIZE_URL));
							}else if($this->option_arr['o_registration_confirmation'] == 'confirm'){
								$this->pjRegistrationConfirmation($id, $group_id);
								header('Location: ' . filter_var($redirectURL . '&reg_err=100', FILTER_SANITIZE_URL));
							}else if($this->option_arr['o_registration_confirmation'] == 'payment'){
								if($amount <= 0)
								{
									$pjMemberModel->reset()->where('id', $id)->limit(1)->modifyAll(array('status' => 'T'));
									header('Location: ' . filter_var($redirectURL . '&reg_err=100', FILTER_SANITIZE_URL));
								}else{
									header('Location: ' . filter_var($redirectURL . '&reg_err=102&group_id=' . $group_id . '&id=' . $id, FILTER_SANITIZE_URL));
								}
							}
						} else {
							header('Location: ' . filter_var($redirectURL . '&reg_err=101', FILTER_SANITIZE_URL));
						}
					}else if(!isset($_GET['log_err'])){
						header('Location: ' . filter_var($redirectURL . '&log_err=105', FILTER_SANITIZE_URL));
					}
				}
			}
		}
		$this->appendCss('front.css');
	}
	public function pjActionGetPaymentForm()
	{
		$this->setAjax(true);
		
		if ($this->isXHR())
		{
			$member_arr = pjMemberModel::factory()->find($_GET['id'])->getData();
			$group_arr = pjGroupModel::factory()->find($member_arr['group_id'])->getData();

			$amount = number_format(floatval($group_arr['registration_fee']) + floatval($group_arr['subscription_fee']), 2, '.', '');
			$subscription_fee = number_format(floatval($group_arr['subscription_fee']), 2, '.', '');
			$item_name = $group_arr['group_title'] . ' ' . pjUtil::formatCurrencySign(floatval($group_arr['registration_fee']), $this->option_arr['o_currency']) . ' ' . __('front_label_registration_fee', true) . ' + ' . pjUtil::formatCurrencySign(floatval($group_arr['subscription_fee']), $this->option_arr['o_currency']) . ' ' . __('front_label_subscription_fee', true);
			$t3 = 'M';
			if ($group_arr['subscription_period'] == 'week')
			{
				$t3 = 'W';
			} else if($group_arr['subscription_period'] == 'year') {
				$t3 = 'Y';
			}
			$this->set('params', array(
				'name' => 'ml_memberlogin_paypal_form',
				'id' => 'ml_memberlogin_paypal_form',
				'business' => $this->option_arr['o_paypal_address'],
				'item_name' => $item_name,
				'custom' => $member_arr['id'],
				'currency_code' => $this->option_arr['o_currency'],
				'return' => $this->option_arr['o_thankyou_page'],
				'notify_url' => PJ_INSTALL_URL . 'index.php?controller=pjFront&action=pjActionConfirmPaypal',
				'target' => '_self',
			
				'amount' => $amount,
	
				'a1_price' => $amount,
				'p1_duration' => 1,
				't1_duration_unit' => $t3,
				
				'a3_price' => $subscription_fee,
				'p3_duration' => 1,
				't3_duration_unit' => $t3,
			
				'recurring_payments' => 1,
				'reattempt_on_failure' => 0
			));
					
			$this->log('submit payment form');
		}
	}
	
	public function pjActionConfirmPaypal()
	{
		$this->setAjax(true);
		
		if (pjObject::getPlugin('pjPaypal') === NULL)
		{
			$this->log('Paypal plugin not installed');
			exit;
		}

		if (!(isset($_POST['custom'], $_POST['txn_id'])))
		{
			$this->log('Missing, empty or invalid parameters (custom, txn_id)');
			exit;
		}
		
		$pjMemberModel = pjMemberModel::factory();
		
		$member_arr = $pjMemberModel
			->select('t1.*, t2.subscription_period, t2.registration_fee, t2.subscription_fee')
			->join('pjGroup', 't2.id=t1.group_id', 'inner')
			->find($_POST['custom'])->getData();
		if (empty($member_arr))
		{
			$this->log('Member not found');
			exit;
		}
		if($member_arr['status'] == 'T')
		{
			$this->log('Member is active.');
			exit;
		}
		switch ($_POST['txn_type'])
		{
			case 'web_accept':
				$amount = (float) $member_arr['registration_fee'];
				$amount_index = 'mc_gross';
				$date_index = 'payment_date';
				break;
			case 'subscr_payment':
				$amount = (float) $member_arr['subscription_fee'];
				if ((int) $member_arr['is_reg_fee_paid'] === 0)
				{
					$amount += (float) $member_arr['registration_fee'];
				}
				$amount_index = 'mc_gross';
				$date_index = 'payment_date';
				break;
			case 'subscr_signup':
				$amount = (float) $member_arr['registration_fee'] + (float) $member_arr['subscription_fee'];
				$amount_index = 'mc_amount1';
				$date_index = 'subscr_date';
				break;
		}

		$txn_id = pjPaypalModel::factory()
			->where('t1.txn_id IS NOT NULL')
			->where('t1.foreign_id', $member_arr['id'])
			->whereIn('t1.txn_type', array('subscr_payment', 'web_accept'))
			->findAll()
			->getDataPair(NULL, 'txn_id');
		
		$params = array(
			'foreign_id' => $member_arr['id'],
			'txn_id' => $txn_id,
			'paypal_address' => $this->option_arr['o_paypal_address'],
			'deposit' => number_format($amount, 2, '.', ''),
			'amount_index' => $amount_index,
			'date_index' => $date_index,
			'currency' => $this->option_arr['o_currency'],
			'key' => md5($this->option_arr['private_key'] . PJ_SALT)
		);
		$response = $this->requestAction(array('controller' => 'pjPaypal', 'action' => 'pjActionConfirm', 'params' => $params), array('return'));
		
		if ($response !== FALSE && $response['status'] === 'OK')
		{
			$this->log('Payment confirmed');
			
			$pjMemberModel->setAttributes(array('id' => $member_arr['id']))->modify(array(
				'status' => 'T',
				'is_reg_fee_paid' => 1
			));
			
			$pjInvoiceModel = pjInvoiceModel::factory();
			$invoice_arr = $pjInvoiceModel
				->where('t1.order_id', $member_arr['uuid'])
				->limit(1)
				->findAll()
				->getData();
			if(count($invoice_arr) == 1)
			{
				$pjInvoiceModel->reset()->set('id', $invoice_arr[0]['id'])->modify(array('status' => 'paid', 'modified' => ':NOW()'));
			}
			
			$this->pjPaymentConfirmation($member_arr['id'], $member_arr['group_id']);
			
		} elseif (!$response) {
			$this->log('Authorization failed');
		} else {
			$this->log('Payment not confirmed');
		}
		header("HTTP/1.1 200 OK");
		exit;
	}
	
	public function pjActionConfirm()
	{
		$id = $_GET['id'];
		$hash = $_GET['hash'];
		if($hash == md5(PJ_SALT . $id))
		{
			$pjMemberModel = pjMemberModel::factory();
			if($pjMemberModel->reset()->where('id', $id)->where('status', 'T')->findCount()->getData() == 0)
			{
				$data = array();
				$data['status'] = 'T';
					
				$pjMemberModel->reset()->where('id', $id)->limit(1)->modifyAll($data);
				
				$err = 'FA01';
			}else{
				$err = 'FA03';
			}
		}else{
			$err = 'FA02';
		}
		$this->set('status', $err);
		$this->appendCss('front.css');
	}
	
	public function pjActionLoginJs()
	{
		header("Content-type: text/javascript");
		$arr = array(
			array('file' => 'jabb-0.4.3.js', 'path' => PJ_LIBS_PATH . 'jabb/'),
			array('file' => 'pjLogin.js', 'path' => PJ_JS_PATH)
		);
		foreach ($arr as $item)
		{
			$js_content = file_get_contents($item['path'] . $item['file']);
			echo $js_content . "\n";
		}
		exit;
	}
	
	public function pjActionLogin()
	{
		$this->setLayout('pjActionFrontJS');
	}
	public function pjActionLoginForm()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			require_once PJ_LIBS_PATH . 'google/Google_Client.php';
			require_once PJ_LIBS_PATH . 'google/contrib/Google_Oauth2Service.php';
			
			$authUrl = '#';
			$loginUrl = '#';
			
			$clientId = $this->option_arr['o_google_client_id'];
			$clientSecret = $this->option_arr['o_google_client_secret'];
			$redirectURL = PJ_INSTALL_URL . 'index.php?controller=pjFront&action=pjActionGoogleLogin';
				
			$gClient = new Google_Client();
			
			$gClient->setApplicationName('Login to Member Login');
			$gClient->setClientId($clientId);
			$gClient->setClientSecret($clientSecret);
			$gClient->setRedirectUri($redirectURL);
				
			$google_oauthV2 = new Google_Oauth2Service($gClient);
			
			$authUrl = $gClient->createAuthUrl();
			
			$appId = $this->option_arr['o_facebook_app_id'];
			$appSecret = $this->option_arr['o_facebook_app_secret'];
			$redirectURL = PJ_INSTALL_URL . 'index.php?controller=pjFront&action=pjActionFacebookLogin';
			$fbPermissions = 'email';
			
			$facebook = new pjFacebook(
			    $appId,
			    $appSecret,
			    $redirectURL
			    );
			
			$user_profile = $facebook->getUser();
			if (!$user_profile)
			{
			    $loginUrl = $facebook->getLoginUrl();
			}
			
			$this->set('authUrl', $authUrl);
			$this->set('loginUrl', $loginUrl);
		}
	}
	public function pjActionForgotForm()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			
		}
	}
	public function pjActionForgotSend()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$json = array();
			$member = pjMemberModel::factory()
				->where('t1.email', $_POST['email'])
				->limit(1)
				->findAll()
				->getData();
			if (count($member) != 1)
			{
				$json['code'] = 101;
			}else{
				$arr = $member[0];
				$email_arr = pjNotificationModel::factory()->where('t1.key', 'forgot')->findAll()->getData();
				if(count($email_arr) > 0)
				{
					$email = $email_arr[0];
					
					$subject = $email['subject'];
					$message = str_replace(	array('{FirstName}', '{Password}'),
											array($arr['first_name'], $arr['password']),
											$email['message']);
					
					$pjEmail = new pjEmail();
					$pjEmail->setContentType('text/html');
					if ($this->option_arr['o_send_email'] == 'smtp')
					{
						$pjEmail
							->setTransport('smtp')
							->setSmtpHost($this->option_arr['o_smtp_host'])
							->setSmtpPort($this->option_arr['o_smtp_port'])
							->setSmtpUser($this->option_arr['o_smtp_user'])
							->setSmtpPass($this->option_arr['o_smtp_pass'])
							->setSender($this->option_arr['o_smtp_user'])
						;
					}
					$pjEmail->setFrom($this->getFromEmail())
								->setTo($arr['email'])
								->setSubject($subject)
								->send($message);
				}
				$json['code'] = 100;
			}
			pjAppController::jsonResponse($json);
		}
		exit;
	}
	
	public function pjActionLoginCheck()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjMemberModel = pjMemberModel::factory();
			
			$json = array();
			
			$member = $pjMemberModel
				->where('t1.email', $_POST['email'])
				->limit(1)
				->findAll()
				->getData();
			if (count($member) != 1)
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => ''));
			}
				
			$member = $pjMemberModel
				->where('t1.id', $member[0]['id'])
				->where(sprintf("t1.password = AES_ENCRYPT('%s', '%s')", $pjMemberModel->escapeStr($_POST['password']), PJ_SALT))
				->limit(1)
				->findAll()
				->getData();
			if(count($member) != 1)
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => ''));
			}
					
			$member = $member[0];
			unset($member['password']);
			
			if ($member['status'] != 'T')
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 103, 'text' => ''));
			}
			
			$group_arr = pjGroupModel::factory()->find($member['group_id'])->getData();
			$amount = floatval($group_arr['registration_fee']) + floatval($group_arr['subscription_fee']);
			if($amount > 0)
			{
				if (empty($member['membership_expire']) || strtotime($member['membership_expire']) <= strtotime(date("Y-m-d")))
				{
					pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 104, 'text' => ''));
				}
			}
							
			$last_login = date("Y-m-d H:i:s");
    		$_SESSION[$this->defaultMember] = $member;
    			
    		# Update
    		$data = array();
    		$data['last_login'] = $last_login;
    		$pjMemberModel->reset()->setAttributes(array('id' => $member['id']))->modify($data);
    			
    		$group_arr = pjGroupModel::factory()
				->find($member['group_id'])
				->getData();
    			
			$json['home_url'] = '';
			if (!empty($group_arr))
			{
				$_arr = parse_url($group_arr['home_url']);
				$scheme = isset($_arr['scheme']) ? $_arr['scheme']. '://' : '';
				$host = isset($_arr['host']) ? $_arr['host'] : '';
				$home_url = str_replace($scheme.$host, "", $group_arr['home_url']);
				$json['home_url'] = $home_url;
			}
    		$json['code'] = 100;
			
			pjAppController::jsonResponse($json);
		}
		exit;
	}
	
	public function pjActionProfileJs()
	{
		header("Content-type: text/javascript");
		$arr = array(
			array('file' => 'jabb-0.4.3.js', 'path' => PJ_LIBS_PATH . 'jabb/'),
			array('file' => 'pjProfile.js', 'path' => PJ_JS_PATH)
		);
		foreach ($arr as $item)
		{
			$js_content = file_get_contents($item['path'] . $item['file']);
			echo $js_content . "\n";
		}
		exit;
	}
	
	public function pjActionProfile()
	{
		$this->setLayout('pjActionFrontJS');
		
		$status = 0;
		
		if(isset($_SESSION[$this->defaultMember]))
		{
			$id = $_SESSION[$this->defaultMember]['id'];
			
			$arr = pjMemberModel::factory()->find($id)->getData();
			
			if (count($arr) === 0)
			{
				$status = 2;
			}else{
				if($arr['status'] != 'T')
				{
					$status = 3;
				}else{
					$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('country_arr', $country_arr);
					$this->set('arr', $arr);
				}
			}
		}else{
			$status = 1;
		}
		
		$this->set('status', $status);
	}
	
	public function pjActionProfileSave()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjMemberModel = pjMemberModel::factory();
			$data = array();
			$birthday = '';
			if (!empty($_POST['day']) && !empty($_POST['month']) && !empty($_POST['year']))
			{
				$data['birthday'] = $_POST['year'] . '-' . $_POST['month'] . '-' . $_POST['day'];
				$birthday = pjUtil::formatDate($data['birthday'], 'Y-m-d', $this->option_arr['o_date_format']);
			}else if (empty($_POST['day']) && empty($_POST['month']) && empty($_POST['year'])){
				$data['birthday'] = ':NULL';
			}
			$data['modified'] = date('Y-m-d H:i:s');
			
			$data = array_merge($_POST, $data);
			
			$pjMemberModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll($data);
			
			echo 100;
		}
		exit;
	}
	
	public function pjActionLogout()
	{
		if(isset($_SESSION[$this->defaultMember]))
		{
			unset($_SESSION[$this->defaultMember]);
		}
		pjUtil::redirect($this->option_arr['o_login_page']);
	}
	
	public function pjActionProtect()
	{
		if(!isset($_SESSION[$this->defaultMember]))
		{
			pjUtil::redirect($this->option_arr['o_protected_page']);
		}
		
		$group_allowed_arr = explode(",", $_GET['group_id']);
		
		if(!in_array($_SESSION[$this->defaultMember]['group_id'], $group_allowed_arr))
		{
			pjUtil::redirect($this->option_arr['o_protected_page']);
		}
	}
	
	public function pjActionFile()
	{
		$this->setLayout('pjActionFrontJS');
		
		if(isset($_SESSION[$this->defaultMember]))
		{
			$group_id = $_SESSION[$this->defaultMember]['group_id'];
			
			$file_arr = pjFileModel::factory()
				->where("(t1.status='T' AND t1.id IN(SELECT TFG.file_id FROM `".pjFileGroupModel::factory()->getTable()."` AS TFG WHERE TFG.group_id IN ($group_id)))")
				->orWhere("(t1.status='T' AND t1.id IN(SELECT TFM.file_id FROM `".pjFileMemberModel::factory()->getTable()."` AS TFM WHERE TFM.member_id=".$_SESSION[$this->defaultMember]['id']."))")
				->findAll()
				->getData();
			$this->set('file_arr', $file_arr);
		}
	}
	
	public function pjActionNoteJs()
	{
		header("Content-type: text/javascript");
		$arr = array(
				array('file' => 'jabb-0.4.3.js', 'path' => PJ_LIBS_PATH . 'jabb/'),
				array('file' => 'pjNotes.js', 'path' => PJ_JS_PATH)
		);
		foreach ($arr as $item)
		{
			$js_content = file_get_contents($item['path'] . $item['file']);
			echo $js_content . "\n";
		}
		exit;
	}
	public function pjActionNote()
	{
		$this->setLayout('pjActionFrontJS');
		
		if(isset($_SESSION[$this->defaultMember])){
						
			$group_id = $_SESSION[$this->defaultMember]['group_id'];
			
			$note_arr = pjNoteModel::factory()					
				->where("(t1.id IN(SELECT TNG.note_id FROM `".pjNoteGroupModel::factory()->getTable()."` AS TNG WHERE TNG.group_id IN ($group_id)) OR t1.id IN(SELECT TNM.note_id FROM `".pjNoteMemberModel::factory()->getTable()."` AS TNM WHERE TNM.member_id=".$_SESSION[$this->defaultMember]['id']."))")
				->where("t1.status", 'T')
				->findAll()
				->getData();
			
			$this->set('note_arr', $note_arr);
		}
	}
	public function pjActionGetNotes()
	{
		if(isset($_SESSION[$this->defaultMember])){
	
			$group_id = $_SESSION[$this->defaultMember]['group_id'];
				
			$note_arr = pjNoteModel::factory()
			->where("(t1.id IN(SELECT TNG.note_id FROM `".pjNoteGroupModel::factory()->getTable()."` AS TNG WHERE TNG.group_id IN ($group_id)) OR t1.id IN(SELECT TNM.note_id FROM `".pjNoteMemberModel::factory()->getTable()."` AS TNM WHERE TNM.member_id=".$_SESSION[$this->defaultMember]['id']."))")
			->where("t1.status", 'T')
			->findAll()
			->getData();
				
			$this->set('note_arr', $note_arr);
		}
	}
	public function pjActionDownloadFile()
	{
		if(isset($_SESSION[$this->defaultMember]))
		{
			$pjFileModel = pjFileModel::factory();
			$group_id = $_SESSION[$this->defaultMember]['group_id'];
			$file_arr = $pjFileModel	
				->where("t1.id IN(SELECT TFG.file_id FROM `".pjFileGroupModel::factory()->getTable()."` AS TFG WHERE TFG.group_id IN ($group_id))")
				->orWhere("t1.id IN(SELECT TFM.file_id FROM `".pjFileMemberModel::factory()->getTable()."` AS TFM WHERE TFM.member_id=".$_SESSION[$this->defaultMember]['id'].")")
				->findAll()
				->getData();
			
			$file_id_arr = array();
			foreach($file_arr as $v)
			{
				$file_id_arr[] = $v['id'];
			}

			if(isset($_GET['id']) && (int) $_GET['id'] > 0 && isset($_GET['hash']))
			{
				if(in_array($_GET['id'], $file_id_arr))
				{
					$id = $_GET['id'];
					$arr = $pjFileModel->reset()->find($id)->getData();
					if(!empty($arr))
					{
						if($arr['status'] == 'T')
						{
							if($_GET['hash'] == sha1(@$arr['id'].@$arr['created'].PJ_SALT))
							{
								pjToolkit::download(@file_get_contents(PJ_INSTALL_URL . $arr['file_path']), $arr['file_name'], $arr['mime_type']);
								exit;
							}else{
								__('front_hash_value_not_match');
							}
						}else{
							__('front_file_disabled');
						}
					}else{
						__('front_file_not_exist');
					}
				}else{
					__('front_no_permissions');
				}
			}else{
				__('front_missing_parameters');
			}
		}
		exit;
	}
	
	protected function pjAdminNotification($member_id, $group_id)
	{
		$arr = pjMemberModel::factory()->find($member_id)->getData();
		$group_arr = pjGroupModel::factory()->find($group_id)->getData();
		$email_arr = pjNotificationModel::factory()->where('t1.key', 'notify')->findAll()->getData();
		if(count($email_arr) > 0)
		{
			$email = $email_arr[0];
			
			$country = '';
			$fee = '';
			$birthday = '';
			$gender = '';
			$gender_arr = __('genderarr', true);
			if(!empty($arr['gender']))
			{
				$gender = $gender_arr[$arr['gender']];
			}
			if(!empty($arr['country_id']))
			{
				$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')->find($arr['country_id'])->getData();
				$country = $country_arr['country_title'];
			}
			
			if(!empty($arr['birthday']))
			{
				$birthday = pjUtil::formatDate($arr['birthday'], 'Y-m-d', $this->option_arr['o_date_format']);
			}
			if(!empty($group_arr['registration_fee']))
			{
				$fee .= __('front_label_registration_fee', true) . ": " . $group_arr['registration_fee'] . $this->option_arr['o_currency'] . "\r\n";
			}
			$period_per = __('period_per', true);
			if(!empty($group_arr['subscription_fee']))
			{
				$fee .= __('front_label_subscription_fee', true) . ": " . $group_arr['subscription_fee'] . $this->option_arr['o_currency'] . " " . $period_per[$group_arr['subscription_period']] . "\r\n";
			}
			$invoiceURL = NULL;
			$pjInvoiceModel = pjInvoiceModel::factory();
			$invoice = $pjInvoiceModel->where('t1.order_id', $arr['uuid'])->orderBy('t1.uuid ASC')->limit(1)->findAll()->getDataIndex(0);
			if(!empty($invoice))
			{
				$invoiceURL = PJ_INSTALL_URL.'index.php?controller=pjInvoice&action=pjActionView&id='.$invoice['id'].'&uuid=' . $invoice['order_id'];
			}
			$subject = $email['subject'];
			$message = str_replace(	array('{Group}', '{FirstName}', '{LastName}', '{Email}', '{Password}', '{Phone}', '{Website}', '{Gender}', '{Age}', '{Birthday}', '{Address}', '{City}', '{State}', '{Country}', '{Zip}', '{CompanyName}', '{CompanyName}', '{Fee}', '{InvoiceURL}'),
									array($group_arr['group_title'], $arr['first_name'], $arr['last_name'], $arr['email'], $arr['password'], $arr['phone'], $arr['website'], $gender, $arr['age'], $birthday, $arr['address'], $arr['city'], $arr['state'], $country, $arr['zip'], $arr['company_name'], $fee, $invoiceURL),
									$email['message']);
			
			$pjEmail = new pjEmail();
			$pjEmail->setContentType('text/html');
			if ($this->option_arr['o_send_email'] == 'smtp')
			{
				$pjEmail
					->setTransport('smtp')
					->setSmtpHost($this->option_arr['o_smtp_host'])
					->setSmtpPort($this->option_arr['o_smtp_port'])
					->setSmtpUser($this->option_arr['o_smtp_user'])
					->setSmtpPass($this->option_arr['o_smtp_pass'])
					->setSender($this->option_arr['o_smtp_user'])
				;
			}
			
			$user_arr = pjUserModel::factory()->where('t1.role_id', 1)->findAll()->getData();
			foreach($user_arr as $admin)
			{
				$pjEmail->setFrom($this->getFromEmail())
						->setTo($admin['email'])
						->setSubject($subject)
						->send($message);
			}
		}
	}
	
	protected function pjRegistrationConfirmation($member_id, $group_id)
	{
		$arr = pjMemberModel::factory()->find($member_id)->getData();
		$group_arr = pjGroupModel::factory()->find($group_id)->getData();
		$email_arr = pjNotificationModel::factory()->where('t1.key', 'register')->findAll()->getData();
		if(count($email_arr) > 0)
		{
			$email = $email_arr[0];
			
			$country = '';
			$birthday = '';
			$fee = '';
			$confirmURL = '';
			$gender = '';
			$gender_arr = __('genderarr', true);
			if(!empty($arr['gender']))
			{
				$gender = $gender_arr[$arr['gender']];
			}
			if(!empty($arr['country_id']))
			{
				$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')->find($arr['country_id'])->getData();
				$country = $country_arr['country_title'];
			}
			$hash = md5(PJ_SALT . $member_id);
			$confirmURL = PJ_INSTALL_URL.'index.php?controller=pjFront&action=pjActionConfirm&id='.$member_id.'&hash='.$hash;
			
			$invoiceURL = NULL;
			$pjInvoiceModel = pjInvoiceModel::factory();
			$invoice = $pjInvoiceModel->where('t1.order_id', $arr['uuid'])->orderBy('t1.uuid ASC')->limit(1)->findAll()->getDataIndex(0);
			if(!empty($invoice))
			{ 
				$invoiceURL = PJ_INSTALL_URL.'index.php?controller=pjInvoice&action=pjActionView&id='.$invoice['id'].'&uuid=' . $invoice['order_id'];
			}
			
			if(!empty($arr['birthday']))
			{
				$birthday = pjUtil::formatDate($arr['birthday'], 'Y-m-d', $this->option_arr['o_date_format']);
			}
			
			if(!empty($group_arr['registration_fee']))
			{
				$fee .= __('front_label_registration_fee', true) . ": " . $group_arr['registration_fee'] . $this->option_arr['o_currency'] . "\r\n";
			}
			$period_per = __('period_per', true);
			if(!empty($group_arr['subscription_fee']))
			{
				$fee .= __('front_label_subscription_fee', true) . ": " . $group_arr['subscription_fee'] . $this->option_arr['o_currency'] . " " . $period_per[$group_arr['subscription_period']] . "\r\n";
			}
			
			$subject = $email['subject'];
			$message = str_replace(	array('{Group}', '{FirstName}', '{LastName}', '{Email}', '{Password}', '{Phone}', '{Website}', '{Gender}', '{Age}', '{Birthday}', '{Address}', '{City}', '{State}', '{Country}', '{Zip}', '{CompanyName}', '{Fee}', '{ConfirmURL}', '{InvoiceURL}'),
									array($group_arr['group_title'], $arr['first_name'], $arr['last_name'], $arr['email'], $arr['password'], $arr['phone'], $arr['website'], $gender, $arr['age'], $birthday, $arr['address'], $arr['city'], $arr['state'], $country, $arr['zip'], $arr['company_name'], $fee, $confirmURL, $invoiceURL),
									$email['message']);
			
			$pjEmail = new pjEmail();
			$pjEmail->setContentType('text/html');
			if ($this->option_arr['o_send_email'] == 'smtp')
			{
				$pjEmail
					->setTransport('smtp')
					->setSmtpHost($this->option_arr['o_smtp_host'])
					->setSmtpPort($this->option_arr['o_smtp_port'])
					->setSmtpUser($this->option_arr['o_smtp_user'])
					->setSmtpPass($this->option_arr['o_smtp_pass'])
					->setSender($this->option_arr['o_smtp_user'])
				;
			}
			$pjEmail->setFrom($this->getFromEmail())
				->setTo($arr['email'])
				->setSubject($subject)
				->send($message);
		}
	}
	
	protected function pjPaymentConfirmation($member_id, $group_id)
	{
		$arr = pjMemberModel::factory()->find($member_id)->getData();
		$group_arr = pjGroupModel::factory()->find($group_id)->getData();
		$email_arr = pjNotificationModel::factory()->where('t1.key', 'payment')->findAll()->getData();
		if(count($email_arr) > 0)
		{
			$email = $email_arr[0];
			
			$country = '';
			$birthday = '';
			$fee = '';
			$confirmURL = '';
			$gender = '';
			$gender_arr = __('genderarr', true);
			if(!empty($arr['gender']))
			{
				$gender = $gender_arr[$arr['gender']];
			}
			if(!empty($arr['country_id']))
			{
				$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')->find($arr['country_id'])->getData();
				$country = $country_arr['country_title'];
			}
			if(!empty($arr['birthday']))
			{
				$birthday = pjUtil::formatDate($arr['birthday'], 'Y-m-d', $this->option_arr['o_date_format']);
			}
			
			if(!empty($group_arr['registration_fee']))
			{
				$fee .= __('front_label_registration_fee', true) . ": " . $group_arr['registration_fee'] . $this->option_arr['o_currency'] . "\r\n";
			}
			$period_per = __('period_per', true);
			if(!empty($group_arr['subscription_fee']))
			{
				$fee .= __('front_label_subscription_fee', true) . ": " . $group_arr['subscription_fee'] . $this->option_arr['o_currency'] . " " . $period_per[$group_arr['subscription_period']] . "\r\n";
			}
			
			$invoiceURL = NULL;
			$pjInvoiceModel = pjInvoiceModel::factory();
			$invoice = $pjInvoiceModel->where('t1.order_id', $arr['uuid'])->orderBy('t1.uuid ASC')->limit(1)->findAll()->getDataIndex(0);
			if(!empty($invoice))
			{
				$invoiceURL = PJ_INSTALL_URL.'index.php?controller=pjInvoice&action=pjActionView&id='.$invoice['id'].'&uuid=' . $invoice['order_id'];
			}
			
			$subject = $email['subject'];
			$message = str_replace(	array('{Group}', '{FirstName}', '{LastName}', '{Email}', '{Password}', '{Phone}', '{Website}', '{Gender}', '{Age}', '{Birthday}', '{Address}', '{City}', '{State}', '{Country}', '{Zip}', '{CompanyName}', '{Fee}', '{InvoiceURL}'),
									array($group_arr['group_title'], $arr['first_name'], $arr['last_name'], $arr['email'], $arr['password'], $arr['phone'], $arr['website'], $gender, $arr['age'], $birthday, $arr['address'], $arr['city'], $arr['state'], $country, $arr['zip'], $arr['company_name'], $fee, $invoiceURL),
									$email['message']);
			
			$pjEmail = new pjEmail();
			$pjEmail->setContentType('text/html');
			if ($this->option_arr['o_send_email'] == 'smtp')
			{
				$pjEmail
					->setTransport('smtp')
					->setSmtpHost($this->option_arr['o_smtp_host'])
					->setSmtpPort($this->option_arr['o_smtp_port'])
					->setSmtpUser($this->option_arr['o_smtp_user'])
					->setSmtpPass($this->option_arr['o_smtp_pass'])
					->setSender($this->option_arr['o_smtp_user'])
				;
			}
			$pjEmail->setFrom($this->getFromEmail())
						->setTo($arr['email'])
						->setSubject($subject)
						->send($message);
		}
	}
	
	protected function pjRegistrationCreated($member_id, $group_id)
	{
		$arr = pjMemberModel::factory()->find($member_id)->getData();
		$group_arr = pjGroupModel::factory()->find($group_id)->getData();
		$email_arr = pjNotificationModel::factory()->where('t1.key', 'created')->findAll()->getData();
		if(count($email_arr) > 0)
		{
			$email = $email_arr[0];
			
			$country = '';
			$birthday = '';
			$fee = '';
			$gender = '';
			$gender_arr = __('genderarr', true);
			if(!empty($arr['gender']))
			{
				$gender = $gender_arr[$arr['gender']];
			}
			if(!empty($arr['country_id']))
			{
				$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')->find($arr['country_id'])->getData();
				$country = $country_arr['country_title'];
			}
			if(!empty($arr['birthday']))
			{
				$birthday = pjUtil::formatDate($arr['birthday'], 'Y-m-d', $this->option_arr['o_date_format']);
			}
			
			if(!empty($group_arr['registration_fee']))
			{
				$fee .= __('front_label_registration_fee', true) . ": " . $group_arr['registration_fee'] . $this->option_arr['o_currency'] . "\r\n";
			}
			$period_per = __('period_per', true);
			if(!empty($group_arr['subscription_fee']))
			{
				$fee .= __('front_label_subscription_fee', true) . ": " . $group_arr['subscription_fee'] . $this->option_arr['o_currency'] . " " . $period_per[$group_arr['subscription_period']] . "\r\n";
			}
			$invoiceURL = NULL;
			$pjInvoiceModel = pjInvoiceModel::factory();
			$invoice = $pjInvoiceModel->where('t1.order_id', $arr['uuid'])->orderBy('t1.uuid ASC')->limit(1)->findAll()->getDataIndex(0);
			if(!empty($invoice))
			{
				$invoiceURL = PJ_INSTALL_URL.'index.php?controller=pjInvoice&action=pjActionView&id='.$invoice['id'].'&uuid=' . $invoice['order_id'];
			}
			$subject = $email['subject'];
			$message = str_replace(	array('{Group}', '{FirstName}', '{LastName}', '{Email}', '{Password}', '{Phone}', '{Website}', '{Gender}', '{Age}', '{Birthday}', '{Address}', '{City}', '{State}', '{Country}', '{Zip}', '{CompanyName}', '{Fee}', 'InvoiceURL'),
									array($group_arr['group_title'], $arr['first_name'], $arr['last_name'], $arr['email'], $arr['password'], $arr['phone'], $arr['website'], $gender, $arr['age'], $birthday, $arr['address'], $arr['city'], $arr['state'], $country, $arr['zip'], $arr['company_name'], $fee, $invoiceURL),
									$email['message']);
			
			$pjEmail = new pjEmail();
			$pjEmail->setContentType('text/html');
			if ($this->option_arr['o_send_email'] == 'smtp')
			{
				$pjEmail
					->setTransport('smtp')
					->setSmtpHost($this->option_arr['o_smtp_host'])
					->setSmtpPort($this->option_arr['o_smtp_port'])
					->setSmtpUser($this->option_arr['o_smtp_user'])
					->setSmtpPass($this->option_arr['o_smtp_pass'])
					->setSender($this->option_arr['o_smtp_user'])
				;
			}
			$pjEmail->setFrom($this->getFromEmail())
						->setTo($arr['email'])
						->setSubject($subject)
						->send($message);
		}
	}
}
?>