<?php

require __DIR__ . '/vendor/autoload.php';

if (empty($_GET['id'])) {
    echo(json_encode([]));
    die();
}

if (empty($_GET['id'])) {
    $resp = ['success' => false, 'error' => 400, 'text' => 'No IDs provided'];
    header('Content-Type: application/json');
    die(json_encode($resp));
}
$config = include __DIR__ . '/config.php';
$internal_pics_dir = realpath(__DIR__ . $config['pics_dir']);
$app = new Phlaym\Roastmonday\Roastmonday($config, $internal_pics_dir);
$app->authenticateServerToken();
$parameters = [
    'include_deleted' => false,
    'include_client' => false,
    'include_counts' => false,
    'include_copy_mentions' => false,
    'include_raw' => false,
    'include_post_raw' => false,
    'include_presence' => true
];
if (!empty($_GET['avatarWidth'])) {
    $parameters['avatarWidth'] = $_GET['avatarWidth'];
}
$resp = ['success' => false, 'error' => 0, 'text' => ''];
try {
    $post = $app->getPost($_GET['id'], $parameters);
} catch (APnutI\Exceptions\NotFoundException $e) {
    $resp['error'] = 404;
} catch (Exception $e) {
    $resp['error'] = 500;
    $resp['text'] = 'Something went wrong';
}
if (!empty($post)) {
    $resp['success'] = true;
    $resp['error'] = 0;
    $resp['text'] = $post->getText(); // DEPRECATED!
    if (!empty($post->user)) {
        $resp['user'] = '@' . $post->user->username;
        if (isset($post->user->name)) {
            $resp['realname'] = $post->user->name;
        }
    }
    if (!empty($post->user) && !empty($post->user->avatar_image) && !empty($post->user->avatar_image->link)) {
        $resp['img'] = $post->user->avatar_image->link;
    }
    $resp['presence'] = $post->user->getPresenceInt();
    $resp['postid'] = $post->id;
    $resp['posttext'] = $post->getText();
    $resp['timestamp'] = $post->created_at->getTimestamp();
}
echo json_encode($resp);
