<?php

$buffer = "\n<!doctype html>\n<html>\n  <head>\n    <title>Multi-Login Demo</title>\n    <link rel='stylesheet' type='text/css' href='css/main.css' media='screen'/>\n    <script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js'></script>\n    <script type='text/javascript' src='js/handlers.js'></script>\n  </head>\n  <body>\n    <article>";
// Set this up so all the data is parsed and packaged to be returned as a nice neat set, and forward the data to the handler variable.
require_once 'vars.php';
require_once 'helpers.php';
$signin_type = $_REQUEST['login_type'];
$provider = empty($_REQUEST['provider']) ? $default : $_REQUEST['provider'];
$domain = $baseurl;
// The return URL is based on a secret and the nearest mod-60-sec microtime.
// Verification is checked against the previous and next mod 60
$returnurl = appendQuery($provider != 'openid' ? "callback=true" : null);
function setAuthParams()
{
    // save the auth data
    // A user is going to authenticate to the server when they need to do a lookup. Encrypted data is encrypted by their salted openid?
}
// display provider switch to the left
$buffer .= "<section id='provider_list'>\n  <ul>\n    <li><a href='?provider=openid'>" . dispSVG('res/openid.svg', 'OpenID', '128', null, 'openid_logo', 'logo_list', true) . "</a></li>\n    <li><a href='?provider=google'>" . dispSVG('res/gplus.svg', 'Google+', '128', null, 'google_logo', 'logo_list', true) . "</a></li>\n    <li><a href='?provider=twitter'>" . dispSVG('res/twitter-bird.svg', 'Twitter', '128', null, 'twitter_logo', 'logo_list', true) . "</a></li>\n    <li><a href='?provider=facebook'>" . dispSVG('res/FB-fLogo.svg', 'Facebook', '128', null, 'facebook_logo', 'logo_list', true) . "</a></li>\n  </ul>\n</section>\n<section id='auth_panel'>";
switch ($provider) {
    case 'google':
        try {
            // try g+ then oauth, THEN openid
            $buffer .= "<script type='text/javascript'>\$('#google_logo').css('opacity','1');</script>";
            try {
                // g+ login
                // can't debug this on rothstein without a higher php version
                // see index.html and the g+ app in ref
                throw new Exception('ForceException');
                $buffer .= "  \n<script type='text/javascript'>\n  (function() {\n    var po = document.createElement('script');\n    po.type = 'text/javascript'; po.async = true;\n    po.src = 'https://plus.google.com/js/client:plusone.js';\n    var s = document.getElementsByTagName('script')[0];\n    s.parentNode.insertBefore(po, s);\n  })();\n  </script>\n  <div id='gConnect'>\n    <button class='g-signin'\n        data-scope='https://www.googleapis.com/auth/plus.login'\n        data-requestvisibleactions='http://schemas.google.com/AddActivity'\n        data-clientId='{{ CLIENT_ID }}'\n        data-accesstype='offline'\n        data-callback='onSignInCallback'\n        data-theme='dark'\n        data-cookiepolicy='single_host_origin'>\n    </button>\n  </div>";
            } catch (Exception $e) {
         # TODO
     }
     break;
 case 'twitter':
     // https://dev.twitter.com/docs/auth/implementing-sign-twitter
     $buffer .= "<script type='text/javascript'>\$('#twitter_logo').css('opacity','1');</script>";
     require_once 'lib/twitteroauth/twitteroauth/twitteroauth.php';
     define("OAUTH_CALLBACK", urlencode($baseurl . "/oauth/oauth.php?provider=twitter"));
     // As readme; save token_credentials as json object in password field
     // Initial implementation as twitteroauth test.php
     // session instances should be replaced with DB calls
     if ($_REQUEST['callback'] != 'true' && $_REQUEST['good_credentials'] != 'true') {
         /* If access tokens are not available redirect to connect page. */
         if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
             //header('Location: ./clearsessions.php'); // fold into major session clearing mode of normal display
             $buffer .= "<p>Need to make a better image.</p><pre>Callback URL: {$returnurl} | " . OAUTH_CALLBACK . "</pre><a href='" . appendQuery('callback=true') . "'>Login with Twitter</a>";
         } else {
             $buffer .= "Temp: Go here to reset this: <a href='http://test.reallyactivepeople.com/oauth/lib/twitteroauth/clearsessions.php'>Test Clearing</a>";
             /* Get user access tokens out of the session. */
             $access_token = $_SESSION['access_token'];
             /* Create a TwitterOauth object with consumer/user tokens. */
             $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
             /* If method is set change API call made. Test is called by default. */
             $content = $connection->get('account/rate_limit_status');
             $buffer .= "<br/>Current API hits remaining: " . $content->remaining_hits;
             /* Get logged in user to help with tests. */
             $user = $connection->get('account/verify_credentials');
             //$buffer.="<pre>".print_r($user,true)."</pre>";
             $hasAuth = true;
             $unique_credentials = array($user->id, $user->url, $user->screen_name);
             $user_special = array("email" => $user->screen_name . "@twitter.com", "picture" => $user->profile_image_url, "full_name" => $user->name, "location" => $user->location, "handle" => $user->screen_name);