<?php

include_once 'common.php';

use Abraham\TwitterOAuth\TwitterOAuth;
use GuzzleHttp\Client;


function sendTwitter()
{
    $token = unserialize($_SESSION['SOCIAL_ACCESS_TOKEN']);
    $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $token['oauth_token'], $token['oauth_token_secret']);

    $data = $connection->post("statuses/update", ["status" => $_POST['status']]);

    // $token = unserialize($_SESSION['SOCIAL_ACCESS_TOKEN']);
    // $client = $token->getHttpClient($configuration);
    // $client->setUri('https://api.twitter.com/1.1/statuses/update.json');
    // $client->setMethod(Zend_Http_Client::POST);
    // $client->setParameterPost('status', $_POST['status']);
    // $response = $client->request();

    // /**
    //  * Check if the json response refers to our tweet details (assume it
    //  * means it was successfully posted). API gurus can correct me.
    //  */
    // $data = json_decode($response->getBody());
    // $result = $response->getBody();
    if (isset($data->text)) {
        $result = 'true';
    } else {
        $result = json_encode($data);
    }
    /**
     * Tweet sent (hopefully), redirect back home...
     */
    //header('Location: ' . URL_ROOT . '?result=' . $result);
    echo ($result);
}

function addHashtagMastodon($status, $hashtag, $group) : string {
    $res = $status;
    $to_add = "";

    if(!str_contains($status, "#$hashtag")) {
        $to_add .= " #$hashtag";
    }
    if(!str_contains($status, $group)) {
        $to_add .= " $group";
    }

    return mb_substr($status,0, 512-mb_strlen($to_add)).$to_add;
}

function sendMastodon()
{
    $token = unserialize($_SESSION['SOCIAL_ACCESS_TOKEN']);
    $domain = $_SESSION['SOCIAL_LOGIN_DOMAIN'];
    $status = addHashtagMastodon($_POST['status'], ltrim($_POST['hashtag'], '#'), $_POST['group']);
    sleep(10);
    $client = new Client([
        'base_uri' => "https://$domain",
        'timeout'  => 2.0,
    ]);
    $resp = $client->post("/api/v1/statuses", [
        'headers' => [
            'Authorization'   => 'Bearer ' . $token,
            'Accept'          => 'application/json',
            'Idempotency-Key' => hash('sha256', $status),
        ],
        'form_params' => [ 'status' => $status ],
    ]);
    echo('true');
}


/**
 * Check for a POSTed status message to send to Twitter
 */
if (
    !empty($_POST) && isset($_POST['status'])
    && isset($_SESSION['SOCIAL_ACCESS_TOKEN'])
) {

    $socialNetwork = isset($_POST['social_network']) ? $_POST['social_network'] : "Twitter";

    if ($socialNetwork == "Twitter") {
        sendTwitter();
    } else {
        sendMastodon();
    }
} else {
    /**
     * Mistaken request? Some malfeasant trying something?
     */
    exit('Invalid tweet request. Oops. Sorry.');
}
