<?php
error_reporting(E_ALL & ~E_NOTICE);

class vB5_Frontend_Controller_Registration extends vB5_Frontend_Controller
{
	/** Responds to a request to create a new user.
	*
	**/
	public function actionRegistration()
	{
		//We need at least a username, email, and password.

		if (empty($_REQUEST['username']) OR empty($_REQUEST['password']) OR empty($_REQUEST['email']))
		{
			$this->sendAsJson(array('error' => 'insufficient data'));
			return;
		}

		$username = trim($_REQUEST['username']);
		$password = trim($_REQUEST['password']);

		$postdata = array('username' => $username, 'email' => $_REQUEST['email']);

		if (isset($_REQUEST['month']) AND isset($_REQUEST['day']) AND !empty($_REQUEST['year']))
		{
			$postdata['birthday'] = $_REQUEST['year'] . '-' . str_pad($_REQUEST['month'], 2, '0', STR_PAD_LEFT) . '-' . str_pad($_REQUEST['day'], 2, '0', STR_PAD_LEFT);
		}

		if (!empty($_REQUEST['guardian']))
		{
			$postdata['parentemail'] = $_REQUEST['guardian'];
		}

		$vboptions = vB5_Template_Options::instance()->getOptions();
		$vboptions = $vboptions['options'];

		// Coppa cookie check
		$coppaage = vB5_Cookie::get('coppaage', vB5_Cookie::TYPE_STRING);
		if ($vboptions['usecoppa'] AND $vboptions['checkcoppa'])
		{
			if ($coppaage)
			{
				$dob = explode('-', $coppaage);
				$month = $dob[0];
				$day = $dob[1];
				$year = $dob[2];
				$postdata['birthday'] = $year . '-' . str_pad($month, 2, '0', STR_PAD_LEFT) . '-' . str_pad($day, 2, '0', STR_PAD_LEFT);
			}
			else
			{
				vB5_Cookie::set('coppaage', $_REQUEST['month'] . '-' . $_REQUEST['day'] . '-' . $_REQUEST['year'], 365, 0);
			}
		}

		$api = Api_InterfaceAbstract::instance();
		$data = array(
			'userid'   => 0,
			'password' => $password,
			'user'     => $postdata,
			array(),
			array(),
			array(),
			array(),
			isset($_REQUEST['humanverify']) ? $_REQUEST['humanverify'] : ''
		);
		if (!empty($_REQUEST['userfield']))
		{
			$data['userfield'] = $_REQUEST['userfield'];
		}
		else
		{
			$data['userfield'] = false;
		}

		// add facebook data
		if ($api->callApi('facebook', 'isFacebookEnabled') && $api->callApi('facebook', 'userIsLoggedIn'))
		{
			$fbUserInfo = $api->callApi('facebook', 'getFbUserInfo');
			$data['user']['fbuserid'] = $fbUserInfo['uid'];
			$data['user']['fbname'] = $fbUserInfo['name'];
			$data['user']['fbjoindate'] = time();

			/*
			echo '<pre>';
			print_r($fbUserInfo);
			print_r($data);
			echo '</pre>';
			exit;
			*/
		}

		// save data
		$response = $api->callApi('user', 'save', $data);

		// save facebook data
		//$api->callApi('facebook', 'saveConnectFacebook', $data);

		if (!empty($response) AND (!is_array($response) OR !isset($response['errors'])))
		{
			// try to login
			$loginInfo = $api->callApi('user', 'login', array($username, $password, '', '', ''));

			if (!isset($loginInfo['errors']) OR empty($loginInfo['errors']))
			{
				// browser session expiration
				vB5_Cookie::set('sessionhash', $loginInfo['sessionhash'], 0, true);
				vB5_Cookie::set('password', $loginInfo['password'], 0);
				vB5_Cookie::set('userid', $loginInfo['userid'], 0);

				$urlPath = '';
				if ($_POST['urlpath'])
				{
					$urlPath = base64_decode(trim($_POST['urlpath']));
				}
				if (!$urlPath OR strpos($urlPath, '/auth/') !== false OR strpos($urlPath, '/register') !== false)
				{
					$urlPath = '/';
				}
				$response = array('urlPath' => $urlPath);
			}
			else if (!empty($loginInfo['errors']))
			{
				$response = array(
					'errors' => $loginInfo['errors']
				);
			}
		}

		if ($vboptions['verifyemail'])
		{
			$response['msg'] = 'registeremail';
			$response['msg_params'] = array($postdata['username'], $postdata['email'], vB5_Config::instance()->baseurl);
		}
		else if ($vboptions['moderatenewmembers'])
		{
			$response['msg'] = 'moderateuser';
			$response['msg_params'] = array($postdata['username'], vB5_Config::instance()->baseurl);
		}
		else
		{
			$routeProfile = $api->callApi('route', 'getUrl', array('route' => 'profile', 'data' => array('userid' => $loginInfo['userid']), array()));
			$routeuserSettings = $api->callApi('route', 'getUrl', array('route' => 'settings', 'data' => array('tab' => 'profile'), array()));
			$routeAccount = $api->callApi('route', 'getUrl', array('route' => 'settings', 'data' => array('tab' => 'account'), array()));
			$response['msg'] = 'registration_complete';
			$response['msg_params'] = array($postdata['username'], 
				vB5_Config::instance()->baseurl . $routeProfile, 
				vB5_Config::instance()->baseurl . $routeAccount, 
				vB5_Config::instance()->baseurl . $routeuserSettings, 
				vB5_Config::instance()->baseurl);
		}

		$this->sendAsJson(array('response' => $response));
	}

	/** Checks whether a user with a specific birthday is COPPA
	 *
	 **/
	public function actionIscoppa()
	{
		$vboptions = vB5_Template_Options::instance()->getOptions();
		$vboptions = $vboptions['options'];

		// Coppaage cookie
		if ($vboptions['usecoppa'] AND $vboptions['checkcoppa'])
		{
			vB5_Cookie::set('coppaage', $_REQUEST['month'] . '-' . $_REQUEST['day'] . '-' . $_REQUEST['year'], 365, 0);
		}

		//Note that 0 = wide open
		// 1 means COPPA users (under 13) can register but need approval before posting
		// 2 means COPPA users cannot register
		$api = Api_InterfaceAbstract::instance();
		$coppa = $api->callApi('user', 'needsCoppa', array('data' => $_REQUEST));
        $this->sendAsJson(array('needcoppa' => $coppa));
	}

	/** Checks whether a user with a specific birthday is COPPA
	 *
	 **/
	public function actionCheckUsername()
	{
		//Note that 0 = wide open
		// 1 means COPPA users (under 13) can register but need approval before posting
		// 2 means COPPA users cannot register
		if (empty($_REQUEST['username']))
		{
			return false;
		}
		$api = Api_InterfaceAbstract::instance();

		$result = $api->callApi('user', 'checkUsername', array('candidate' => $_REQUEST['username']));
        $this->sendAsJson($result);
	}

	/**
	 * Activate an user who is in "Users Awaiting Email Confirmation" usergroup
	 */
	public function actionActivateUser()
	{
		$get = array(
			'u' => !empty($_GET['u']) ? intval($_GET['u']) : 0, // Userid
			'i' => !empty($_GET['i']) ? trim($_GET['i']) : '', // Activate ID
		);

		$api = Api_InterfaceAbstract::instance();
		$result = $api->callApi('user', 'activateUser', array('userid' => $get['u'], 'activateid' => $get['i']));

		$phrasevars = array('registration');

		if (!empty($result['errors']) AND is_array($result['errors']))
		{
			if (is_array($result['errors'][0]))
			{
				$messagevar = array_shift($result['errors'][0]);
			}
			else
			{
				$messagevar = $result['errors'][0];
			}
		}
		else
		{
			$messagevar = $result;
		}

		$phrasevars[] = $messagevar;
		$phrases = $api->callApi('phrase', 'fetch', array($phrasevars));
		$this->showMsgPage($phrases['registration'], $phrases[$messagevar]);

	}

}
