<?php
// This script checks the JSON file for existing users and updates their newest post date + URL if newer ones exist.

$filename = 'fedimissing.json';

// Ensure file exists
if (!file_exists($filename)) {
    die("JSON file not found: $filename");
}

// Load JSON
$json_content = file_get_contents($filename);
if ($json_content === false) {
    die("Error reading JSON file.");
}

$json_data = json_decode($json_content, true);
if (!is_array($json_data)) {
    die("Invalid JSON format.");
}

// Configure HTTP context
$context = stream_context_create([
    'http' => [
        'timeout' => 15,
        'header' => "User-Agent: FediversePostUpdater/1.0\r\nAccept: application/json\r\n"
    ],
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false
    ]
]);

// Iterate over all entries
foreach ($json_data as &$entry) {
    $username = $entry['username']; // e.g. @user@domain
    $parts = explode('@', $username);

    if (count($parts) < 3) {
        echo "Skipping invalid username format: $username<br>";
        continue;
    }

    $local_user = $parts[1];
    $domain = $parts[2];

    // Look up account to get ID
    $lookup_urls = [
        "https://$domain/api/v1/accounts/lookup?acct=" . urlencode("$local_user@$domain"),
        "https://$domain/users/" . urlencode($local_user) . ".json",
    ];

    $account_data = null;
    foreach ($lookup_urls as $lookup_url) {
        $response = @file_get_contents($lookup_url, false, $context);
        if ($response !== false) {
            $account_data = json_decode($response, true);
            if ($account_data) break;
        }
    }

    $user_id = null;
    if ($account_data && isset($account_data['id'])) {
        $user_id = $account_data['id'];
    }

    $latest_post_url = null;
    $created_at = null;

    if ($user_id) {
        // Get statuses by user ID
        $statuses_url = "https://$domain/api/v1/accounts/$user_id/statuses?limit=1";
        $response = @file_get_contents($statuses_url, false, $context);
        if ($response !== false) {
            $statuses = json_decode($response, true);
            if (is_array($statuses) && !empty($statuses)) {
                $created_at = $statuses[0]['created_at'];
                if (isset($statuses[0]['url'])) {
                    $latest_post_url = $statuses[0]['url'];
                }
            }
        }
    }

    if (!$created_at) {
        echo "No posts found for $username<br>";
        continue;
    }

    // Format date
    $date = date('Ymd', strtotime($created_at));

    // Only update if date is newer
    if ($date > $entry['date']) {
        $entry['date'] = $date;
        $entry['post_url'] = $latest_post_url;
        echo "Updated $username → $date ($latest_post_url)<br>";
    } else {
        echo "No new posts for $username (latest: {$entry['date']})<br>";
    }
}

// Save updated JSON
if (file_put_contents($filename, json_encode($json_data, JSON_PRETTY_PRINT))) {
    echo "<br>JSON file updated successfully.";
} else {
    echo "<br>Error saving JSON file. Check permissions.";
}
?>
