<?php
require_once 'libraries/gpConfig.php';
require_once 'libraries/fbConfig.php';

if ( \S::get( 'a' ) == 'contact_form_send' )
{    
  $response = [ 'status' => 'error' ];  
  
  if ( ( \S::get( 'email' ) and \S::get( 'name' ) and \S::get( 'text' ) ) )
  {
    if ( \S::send_email( 
            $settings['contact_email'],
            \S::get( 'subject' ),
            '<p>Nadawca: ' . \S::get( 'name' ) . '</p>'
            . '<p>Nr telefonu: ' . \S::get( 'phone' ) . '</p>'
            . '<p>Email: ' . \S::get( 'email' ) . '</p>'
            . '<p>' . \S::get( 'text' ) . '</p>',
            $settings['contact_email'] 
          ) )
          $response = [ 'status' => 'ok' ]; 
  }
  echo json_encode( $response );
  exit;
}

/* logowanie google */
if ( isset( $_GET['code'] ) and $_GET['scope'] and !$_SESSION['token'] )
{
  $gClient -> authenticate( $_GET['code'] );
  $_SESSION['token'] = $gClient -> getAccessToken();
}

if ( isset( $_SESSION['token'] ) )
  $gClient -> setAccessToken( $_SESSION['token'] );

if ( $gClient -> getAccessToken() ) 
{
  $gpUserProfile = $google_oauthV2 -> userinfo -> get();
  
  parse_str( $_GET['state'] );
  
  if ( $gpUserProfile['id'] )
  {
    if ( !$mdb -> count( 'globelus_users', 'id', [ 'AND' => [ 'oauth_uid' => $gpUserProfile['id'], 'oauth_provider' => 'google' ] ] ) )
    {
      if ( $g_register )
      {
        if ( $mdb -> count( 'globelus_users', 'id', [ 'email' => $gpUserProfile['email'] ] ) )
        {
          unset( $_SESSION['token'] );
          \S::alert( 'Podany adres email jest już zajęty.' );
        }
        else
        {
          /* dodawanie użytkownika */
          $hash           = md5( time() . $gpUserProfile['email'] );
          $register_date  = date('Y-m-d H:i:s');

          $mdb -> insert( 'globelus_users', [
                    'email'                     => $gpUserProfile['email'],
                    'hash'                      => $hash,
                    'type'                      => (int)$g_type,
                    'user_agremment_profile'    => 1,
                    'user_agremment_marketing'  => 1,
                    'register_date'             => $register_date,
                    'active_to'                 => date( 'Y-m-d', strtotime( '+90 days', time() ) ),
                    'oauth_uid'                 => $gpUserProfile['id'],
                    'oauth_provider'            => 'google'
                  ] );
          \front\factory\GlobelusUser::signin( $gpUserProfile['email'], null, $gpUserProfile['id'], 'google' );
        }
      }
      else
      {
        unset( $_SESSION['token'] );
        \S::alert( $lang['logowanie-blad-brak-konta'] );
      }
    }
    else
      \front\factory\GlobelusUser::signin( $gpUserProfile['email'], null, $gpUserProfile['id'], 'google' );
    
    $g_user = \S::get_session( 'g_user' );

    if ( $g_user and !$g_user['profile_completed'] and $g_user['type'] )
      \S::alert( 'Nie posiadasz uzupełnionego profilu.' );
  }
}

/* logowanie Facebook */
if ( $accessToken and !isset( $g_type ) )
{
  if ( isset( $_SESSION['facebook_access_token'] ) )
		$fb -> setDefaultAccessToken( $_SESSION['facebook_access_token'] );
	else
  {
    $_SESSION['facebook_access_token']  = (string) $accessToken;
    $oAuth2Client                       = $fb -> getOAuth2Client();
    $longLivedAccessToken               = $oAuth2Client -> getLongLivedAccessToken( $_SESSION['facebook_access_token'] );
    $_SESSION['facebook_access_token']  = (string) $longLivedAccessToken;
    $fb -> setDefaultAccessToken( $_SESSION['facebook_access_token'] );

    $profileRequest = $fb -> get( '/me?fields=name,first_name,last_name,email,link,gender,locale,cover,picture' );
    $fbUserProfile = $profileRequest -> getGraphNode() -> asArray();

    if ( $fbUserProfile['id'] )
    {
      if ( !$mdb -> count( 'globelus_users', 'id', [ 'AND' => [ 'oauth_uid' => $fbUserProfile['id'], 'oauth_provider' => 'facebook' ] ] ) )
      {
        if ( \S::get( 'f_register' ) )
        {
          if ( $mdb -> count( 'globelus_users', 'id', [ 'email' => $fbUserProfile['email'] ] ) )
          {
            unset( $_SESSION['facebook_access_token'] );
            \S::alert( 'Podany adres email jest już zajęty.' );
          }
          else
          {
            /* dodawanie użytkownika */
            $hash           = md5( time() . $fbUserProfile['email'] );
            $register_date  = date('Y-m-d H:i:s');

            $mdb -> insert( 'globelus_users', [
                      'email'                     => $fbUserProfile['email'],
                      'hash'                      => $hash,
                      'type'                      => (int)\S::get( 'f_type' ),
                      'user_agremment_profile'    => 1,
                      'user_agremment_marketing'  => 1,
                      'register_date'             => $register_date,
                      'active_to'                 => date( 'Y-m-d', strtotime( '+90 days', time() ) ),
                      'oauth_uid'                 => $fbUserProfile['id'],
                      'oauth_provider'            => 'facebook'
                    ] );
            \front\factory\GlobelusUser::signin( $fbUserProfile['email'], null, $fbUserProfile['id'], 'facebook' );
          }
        }
        else
        {
          unset( $_SESSION['facebook_access_token'] );
          \S::alert( $lang['logowanie-blad-brak-konta'] );
        }
      }
      else
        \front\factory\GlobelusUser::signin( $fbUserProfile['email'], null, $fbUserProfile['id'], 'facebook' );

      $g_user = \S::get_session( 'g_user' );

      if ( $g_user and !$g_user['profile_completed'] and $g_user['type'] )
        \S::alert( 'Nie posiadasz uzupełnionego profilu.' );
    }
	}
}

if ( isset( $_GET['code'] ) )
{
  header( 'Location: /' );
  exit;
}