<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS\module\members
 * @copyright Copyright (c) 2016 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/**
 * membersFacebook Class
 *
 * Class to implement Facebook integration.
 *
 * @package clearFusionCMS\module\members
 */
class membersFacebook {

	/**
	 * Do the facebook login.
	 * 
	 * @param cfTemplateEngine $tplEngine The template engine.
	 * @param string $onLoggedIn The page to go to on login or null.
	 * @param string $label Optional label for the login button or null.
	 * @return string The login label html
	 */
	static function doLogin($tplEngine, $onLoggedIn, $label = null) {
		static $first = true;

		$controller = $tplEngine->controller;

		// If already logged in then send to destination page
		if(clearFusionCMS::getUser()->isAuthenticated()) {
			if($onLoggedIn)
				$controller->getResponse()->redirectTo($controller->content->getPageURI($onLoggedIn, true));
		}
		else {
			$request = $controller->getRequest();

			if ($request->isXmlHttpRequest() && $request->isPost()) {
				$token = $request->getPost('fbAccessToken', '');

				$userInfo = cfFacebook::getUserInfo($token);

				$r = array(
					'success' => false,
					'msg' => __('Failed to login with Facebook', 'members')
				);

				if ($userInfo) {
					if (!empty($userInfo->email)) {
						// Auth the user by Facebook user ID
						$user = clearFusionCMS::getUser();
						$auth = $user->authenticate('facebook', $userInfo->id, false, 'external');

						$uMgr = clearFusionCMS::getUserMgr();

						// If not authed try to create a new user
						if (!$auth) {
							$uList = $uMgr->find($userInfo->email, array('email'), true);

							// If no users exist with the email address
							if (!count($uList)) {

								// Create the new user
								if ($uid = $uMgr->create(null, $userInfo->email, array('service' => 'facebook', 'authcode' => $userInfo->id), 'active', clearFusionCMS::getSysTimezone(), $userInfo->name)) {
									// Set the default roles for the user
									$cfg = clearFusionCMS::getSiteConfig('cfMembers');
									$uMgr->setUserRoles($uid, unserialize($cfg->defaultRoles));

									// Auth the user
									$uMgr->authUser($tplEngine->controller->getResponse(), $uid);

									$r['success'] = true;
									if($onLoggedIn)
										$r['redirect'] = $controller->content->getPageURI($onLoggedIn, true);
								}
							} else {
								$r['msg'] = __('You user account does not use login with Facebook, please try another method to login.', 'members');
							}
						} else {
							// Update the users email to keep it in sync
							$uMgr->setEmail($user->getId(), $userInfo->email);

							$r['success'] = true;
							if($onLoggedIn)
								$r['redirect'] = $controller->content->getPageURI($onLoggedIn, true);
						}
					}
				}

				$tplEngine->controller->getResponse()
					->noCache()
					->setContentType('application/json')
					->setBody(json_encode(
						$r
					))
					->sendResponse();
				die;
			}

			return cfFacebook::getConnect($tplEngine, $controller->getRequest()->getSelf(), 'public_profile,email', $label);
		}
	}
}