<!--autofill-->
<script>
document.addEventListener('DOMContentLoaded', () => {
  function getQueryParams() {
    const params = {};
    location.search.substring(1).split("&").forEach(pair => {
      if (!pair) return;
      const [key, value] = pair.split("=").map(decodeURIComponent);
      params[key] = value;
    });
    return params;
  }

  const params = getQueryParams();

  if (params.userinstance) {
    const el = document.querySelector('input[name="your_instance"]');
    if (el) el.value = params.userinstance;
  }

  if (params.apikey) {
    const el = document.querySelector('input[name="access_token"]');
    if (el) el.value = params.apikey;
  }

  if (params.instancetofollow) {
    const el = document.querySelector('input[name="remote_user"]');
    if (el) el.value = params.instancetofollow;
  }
});
</script>

<?php
function resolveAcct(string $input): array {
    $input = trim($input);
    $input = ltrim($input, '@');
    if (strpos($input, '@') === false) {
        return ['', ''];
    }
    return explode('@', $input, 2);
}

function domainFromUrl(string $url): string {
    $parts = parse_url($url);
    return $parts['host'] ?? '';
}

function remoteFetch(string $yourInstance, string $accessToken, string $remoteUser, string $remoteDomain): bool {
    $ch = curl_init();

    $fetchUrl = $yourInstance . '/api/v1/follow_requests/remote?acct=' . urlencode("$remoteUser@$remoteDomain");
    // Note: Mastodon API does not have a direct "remote fetch" endpoint in stable versions,
    // but some instances support "POST /api/v1/follows" with acct param to fetch remote users.
    // We'll try that fallback:

    $followUrl = $yourInstance . '/api/v1/follows';

    curl_setopt($ch, CURLOPT_URL, $followUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['uri' => "$remoteUser@$remoteDomain"]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $accessToken"]);

    $response = curl_exec($ch);
    curl_close($ch);

    if ($response === false) {
        return false;
    }
    $data = json_decode($response, true);
    // If data has "id", assume fetched successfully
    return isset($data['id']);
}

$yourInstance = $_POST['your_instance'] ?? '';
$accessToken = $_POST['access_token'] ?? '';
$remoteUserRaw = $_POST['remote_user'] ?? '';
$result = '';
$error = '';
$offerFetch = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $yourInstance = rtrim(trim($yourInstance), '/');
    $accessToken = trim($accessToken);
    $remoteUserRaw = trim($remoteUserRaw);

    list($remoteUser, $remoteDomain) = resolveAcct($remoteUserRaw);

    if ($yourInstance === '' || $accessToken === '' || $remoteUser === '' || $remoteDomain === '') {
        $error = "Your Instance URL, Access Token, and Remote User (user@domain) are required.";
    } else {
        $ch = curl_init();

        // Search using just the username (remoteUser)
        $searchUrl = $yourInstance . '/api/v2/search?q=' . urlencode($remoteUser) . '&type=accounts&limit=10';
        curl_setopt($ch, CURLOPT_URL, $searchUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $accessToken"]);
        $searchResponse = curl_exec($ch);

        if ($searchResponse === false) {
            $error = "Search failed: " . curl_error($ch);
        } else {
            $searchData = json_decode($searchResponse, true);

            $foundUser = null;
            foreach ($searchData['accounts'] ?? [] as $account) {
                if (strcasecmp($account['acct'] ?? '', "$remoteUser@$remoteDomain") === 0) {
                    $foundUser = $account;
                    break;
                }
                if (domainFromUrl($account['url'] ?? '') === $remoteDomain) {
                    $acctUser = explode('@', $account['acct'])[0];
                    if (strcasecmp($acctUser, $remoteUser) === 0) {
                        $foundUser = $account;
                        break;
                    }
                }
            }

            if (!$foundUser) {
                // Offer remote fetch option
                $offerFetch = true;
                $error = "Remote user not found or not federated yet. You can try to fetch the remote user first.";
            } else {
                // Verify credentials (get own user id)
                $verifyUrl = $yourInstance . '/api/v1/accounts/verify_credentials';
                curl_setopt($ch, CURLOPT_URL, $verifyUrl);
                curl_setopt($ch, CURLOPT_HTTPGET, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $accessToken"]);
                $verifyResp = curl_exec($ch);

                if ($verifyResp === false) {
                    $error = "Verify credentials failed: " . curl_error($ch);
                } else {
                    $myData = json_decode($verifyResp, true);
                    if (isset($myData['id']) && $myData['id'] == $foundUser['id']) {
                        $error = "Cannot follow your own account.";
                    } else {
                        $userId = $foundUser['id'];

                        $followUrl = $yourInstance . "/api/v1/accounts/$userId/follow";
                        curl_setopt($ch, CURLOPT_URL, $followUrl);
                        curl_setopt($ch, CURLOPT_POST, true);
                        curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $accessToken"]);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        $followResponse = curl_exec($ch);

                        if ($followResponse === false) {
                            $error = "Follow failed: " . curl_error($ch);
                        } else {
                            $result = $followResponse;
                        }
                    }
                }
            }
        }
        curl_close($ch);
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['remote_fetch'])) {
    // User requested remote fetch
    list($remoteUser, $remoteDomain) = resolveAcct($remoteUserRaw);
    if ($yourInstance !== '' && $accessToken !== '' && $remoteUser !== '' && $remoteDomain !== '') {
        if (remoteFetch($yourInstance, $accessToken, $remoteUser, $remoteDomain)) {
            $result = "Remote user fetched successfully. Please try following again.";
            $offerFetch = false;
        } else {
            $error = "Remote fetch failed.";
        }
    } else {
        $error = "Invalid data for remote fetch.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Remote Follow via Mastodon API</title>
<style>
    body { font-family: sans-serif; max-width: 600px; margin: 2em auto; }
    label { display: block; margin-top: 1em; }
    input[type=text], input[type=password] { width: 100%; padding: 0.5em; font-size: 1em; }
    button { margin-top: 1em; padding: 0.5em 1em; font-size: 1em; }
    pre { background: #eee; padding: 1em; white-space: pre-wrap; word-wrap: break-word; }
</style>
</head>
<body>

<h1>Remote Follow on Mastodon</h1>
<form method="POST" autocomplete="off">
    <label>
        Your Mastodon Instance URL:<br />
        <input type="text" name="your_instance" value="<?= htmlspecialchars($yourInstance) ?>" placeholder="https://mastodon.social" required />
    </label>
    <label>
        Your Access Token:<br />
        <input type="password" name="access_token" value="<?= htmlspecialchars($accessToken) ?>" required />
    </label>
    <label>
        Remote User (user@domain or @user@domain):<br />
        <input type="text" name="remote_user" value="<?= htmlspecialchars($remoteUserRaw) ?>" placeholder="alcea@animexx.de" required />
    </label>
    <button type="submit" name="follow">Follow User</button>
</form>

<?php if ($error): ?>
    <h2 style="color:red">Error</h2>
    <pre><?= htmlspecialchars($error) ?></pre>
<?php endif; ?>

<?php if ($offerFetch): ?>
<form method="POST" autocomplete="off" style="margin-top: 2em;">
    <input type="hidden" name="your_instance" value="<?= htmlspecialchars($yourInstance) ?>" />
    <input type="hidden" name="access_token" value="<?= htmlspecialchars($accessToken) ?>" />
    <input type="hidden" name="remote_user" value="<?= htmlspecialchars($remoteUserRaw) ?>" />
    <button type="submit" name="remote_fetch">Fetch Remote User</button>
</form>
<?php endif; ?>

<?php if ($result && !$offerFetch): ?>
    <h2>Response</h2>
    <pre><?= htmlspecialchars($result) ?></pre>
<?php endif; ?>

</body>
</html>
