<?php

require './inc/config.inc.php';
require './inc/header.php';
try {
    $m = new YahooMessageArchiver(TRUE);
} catch (OauthException $e) {
    echo "ERROR: Response: " . $e->lastResponse . PHP_EOL;
    exit;
}
// @todo make output prettier instead of print_r() everywhere
try {
    $info = $m->getStoredInfo();
    echo '<h3>Stored authentication information</h3>', PHP_EOL;
    echo '<p>GUID of user: '******'xoauth_yahoo_guid'], '</p>', PHP_EOL;
    echo '<p>Additional information is saved.</p>';
    echo '<h3>All leagues you have played in</h3>', PHP_EOL;
    $ids = $m->getLeagueIds(FALSE);
    echo '<dl>';
    foreach ($ids as $id) {
        // @todo A few are missing this, research this
        if (FALSE === strpos($id['url'], 'http://')) {
            $id['url'] = 'http://football.fantasysports.yahoo.com' . $id['url'];
        }
        echo '<dt><a href="', $id['url'], '">', $id['name'], '</a></dt>', PHP_EOL;
        echo '<dd>League Key: ', $id['league_key'], ' with ', $id['num_teams'], ' teams</dd>', PHP_EOL;
        // @todo Somtimes an empty object, research this, because league has not started? What does 'update' mean?
        $time = $id['league_update_timestamp'];
        if (is_object($time)) {
            $time = 'unknown';
        } else {
             $m->printR($m->getLog());
             echo 'Error: Did not receive authentication url. Hmm...', PHP_EOL;
             exit;
         }
         header('Location: ' . $response['xoauth_request_auth_url']);
         exit;
     } else {
         // @todo add error reporting
         echo 'Error: Unknown problem.' . PHP_EOL;
         exit;
     }
 }
 /********************************************************************************************************************************************
 	/** Stage #2: Access Token
 	/********************************************************************************************************************************************/
 if (!($request_token_info = $m->getStoredInfo())) {
     echo 'Error: Unable to locate request token information. Try requesting it again.', PHP_EOL;
     $m->printR($m->getLog());
     exit;
 }
 if (empty($request_token_info)) {
     echo 'Error: no request information, info is empty. Try requesting it again.', PHP_EOL;
     exit;
 }
 if ($request_token_info && is_array($request_token_info)) {
     $o->setToken($request_token_info['oauth_token'], $request_token_info['oauth_token_secret']);
     if (empty($_GET['oauth_verifier'])) {
         echo 'Missing oauth_verifier.', PHP_EOL;
         exit;
     }
     $response = $o->getAccessToken('https://api.login.yahoo.com/oauth/v2/get_token', NULL, $_GET['oauth_verifier']);