<?php

use System\Response;
use System\Session;
use System\Config;

$fbObj = new \Facebook\Facebook([
'app_id' => Config::social('facebook')['app_id'],
'app_secret' => Config::social('facebook')['app_secret'],
'default_graph_version' => 'v2.7'
]);

$helper = $fbObj->getRedirectLoginHelper();

// if there is no code get one then
if(!isset($_GET['code']) || empty($_GET['code'])){
  $permissions = ['public_profile','email']; 
  $loginUrl = $helper->getLoginUrl(Config::social('facebook')['call_back'], $permissions);
  header('Location: ' .$loginUrl);
  exit;
}

try {

  $accessToken = $helper->getAccessToken();

}catch(Facebook\Exceptions\FacebookResponseException $e) {
   SomethingWrong('login');

} catch(Facebook\Exceptions\FacebookSDKException $e) {
  SomethingWrong('login');
}

// if still there is some error
if(!isset($accessToken) && $accessToken) Response::redirect(href('login'));

try {

  $response = $fbObj->get('/me?locale=en_US&fields=id, email, name', $accessToken);

} catch(\Facebook\Exceptions\FacebookResponseException $e) {
  SomethingWrong('login');

} catch(\Facebook\Exceptions\FacebookSDKException $e) {
  SomethingWrong('login');
}

$fbUser = $response->getGraphUser();

// current data
$fbData = current($fbUser);

// if not complete data
if(!$fbData['email'] && !$fbData['name'] && !$fbData['id']) SomethingWrong('login');

// if there is count simply login the user
if($usero->login($fbData['email'], null, 'yes'))
    Response::redirect('/');

// else he's new lets add this one
$userFields = [
    'username' => $fbData['id'],
    'email' => $fbData['email'],
    'role' => 'user',
    'status' => 'active'
];

$usero->create($userFields);

// now try to login again
if($usero->login($fbData['email'], null, 'yes'))
    Response::redirect('/');

SomethingWrong('login');