<?php
namespace Misuzu;

use Misuzu\Users\User;
use Misuzu\Twitter\TwitterAccessToken;
use Misuzu\Twitter\TwitterClient;

require_once '../../../misuzu.php';

if(!User::hasCurrent() || !perms_check_user(MSZ_PERMS_GENERAL, User::getCurrent()->getId(), MSZ_PERM_GENERAL_MANAGE_TWITTER)) {
    echo render_error(403);
    return;
}

$tCfg = $cfg->scopeTo('twitter');

$tClient = $msz->createTwitterClient();
$tHasClientId = $tClient->hasClientId();
$tHasAccessToken = $tClient->hasAccessToken();
$tHasRefreshToken = $tClient->hasRefreshToken();
$tExpires = $tClient->getAccessToken()->getExpiresTime();

if(isset($_GET['m'])) {
    if(CSRF::validateRequest()) {
        $mode = (string)filter_input(INPUT_GET, 'm');

        if($mode === 'authorise' && $tHasClientId && !$tHasAccessToken) {
            $tAuthorise = $tClient->authorise(TwitterClient::SYSTEM_SCOPES, url_prefix(false) . url('twitter-callback'));
            setcookie('msz_twitter', $tAuthorise->getVerifier(), strtotime('+5 minutes'), '/', msz_cookie_domain(), !empty($_SERVER['HTTPS']), true);
            header('Location: ' . $tAuthorise->getUri());
            return;
        }

        if($mode === 'refresh' && $tHasClientId && $tHasAccessToken && $tHasRefreshToken) {
            $tRefresh = TwitterAccessToken::fromTwitterResponse($tClient->authRefresh());
            TwitterAccessToken::save($tCfg->scopeTo('access'), $tRefresh);
            header('Location: ' . url('manage-general-twitter'));
            return;
        }

        if($mode === 'revoke' && $tHasClientId && $tHasAccessToken) {
            $tRevoke = $tClient->authRevoke();
            if(!empty($tRevoke->revoked))
                TwitterAccessToken::nuke($tCfg->scopeTo('access'));

            header('Location: ' . url('manage-general-twitter'));
            return;
        }
    }

    header('Location: ' . url('manage-general-twitter'));
    return;
}

Template::render('manage.general.twitter', [
    'twitter_has_oauth2' => $tHasClientId,
    'twitter_has_access' => $tHasAccessToken,
    'twitter_has_refresh' => $tHasRefreshToken,
    'twitter_expires' => $tExpires,
]);
