<?php
// Handle the form submission and processing
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the Fediverse URL from the POST request
    $fediverse_url = trim($_POST['fediverse_url']);

    // Validate the URL (basic validation)
    if (!filter_var($fediverse_url, FILTER_VALIDATE_URL)) {
        die("Invalid URL.");
    }

    // Parse the URL
    $parsed_url = parse_url($fediverse_url);
    if (!isset($parsed_url['host'])) {
        die("Invalid URL structure.");
    }
    
    $domain = $parsed_url['host'];
    $path = $parsed_url['path'];
    
    // Extract username from different URL formats
    $username = null;
    $status_id = null;
    
    // Pattern for Mastodon/Pleroma/Akkoma post URLs: /@user/123456
    if (preg_match('#^/(@[^/]+)/(\d+)$#', $path, $matches)) {
        $username = $matches[1];
        $status_id = $matches[2];
    } 
    // Pattern for user profile URLs: /@user
    else if (preg_match('#^/(@[^/]+)$#', $path, $matches)) {
        $username = $matches[1];
    }
    // Pattern for Pleroma/Akkoma notice URLs: /notice/ABC123
    else if (preg_match('#^/notice/([^/]+)$#', $path, $matches)) {
        $status_id = $matches[1];
    }
    // Pattern for Akkoma objects: /objects/ABC123
    else if (preg_match('#^/objects/([^/]+)$#', $path, $matches)) {
        $status_id = $matches[1];
    }
    // Pattern for Akkoma users: /users/username
    else if (preg_match('#^/users/([^/]+)$#', $path, $matches)) {
        $username = '@' . $matches[1];
    }
    else {
        die("Unsupported URL format: $path");
    }
    
    // Configure HTTP context
    $context = stream_context_create([
        'http' => [
            'timeout' => 15,
            'header' => "User-Agent: FediversePostFetcher/1.0\r\nAccept: application/json\r\n"
        ],
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false
        ]
    ]);
    
    // If we have a status ID but no username, fetch the post to get the username
    if ($status_id && !$username) {
        // Try different API endpoints for different platforms
        $api_urls = [
            "https://$domain/api/v1/statuses/$status_id", // Mastodon/Pleroma standard
            "https://$domain/objects/$status_id", // Akkoma alternative
        ];
        
        $post_data = null;
        foreach ($api_urls as $api_url) {
            $response = @file_get_contents($api_url, false, $context);
            if ($response !== false) {
                $post_data = json_decode($response, true);
                if ($post_data) break;
            }
        }
        
        if (!$post_data) {
            die("Error fetching post data from the server.");
        }
        
        // Extract username from post data - ensure we get the full @user@domain format
        if (isset($post_data['account']['acct'])) {
            $acct = $post_data['account']['acct'];
            // Check if the acct already contains a domain
            if (strpos($acct, '@') === false) {
                // If not, add the domain
                $username = '@' . $acct . '@' . $domain;
            } else {
                $username = '@' . $acct;
            }
        } else if (isset($post_data['account']['username'])) {
            $acct = $post_data['account']['username'];
            // Try to get the full acct (username@domain) if possible
            if (isset($post_data['account']['url'])) {
                $account_url = parse_url($post_data['account']['url']);
                if (isset($account_url['host']) && $account_url['host'] !== $domain) {
                    $username = '@' . $acct . '@' . $account_url['host'];
                } else {
                    $username = '@' . $acct . '@' . $domain;
                }
            } else {
                $username = '@' . $acct . '@' . $domain;
            }
        } else {
            die("Unable to extract user information from post.");
        }
    } else if ($username) {
        // If we already have a username from the URL, ensure it's in the full @user@domain format
        $username_parts = explode('@', $username);
        if (count($username_parts) === 2) {
            // Only username part is present, add domain
            $username = $username . '@' . $domain;
        }
    }
    
    // Now get the user's latest post using the username
    // Extract just the username part without @ for lookup
    $lookup_username = substr($username, 1); // Remove the leading @
    $lookup_username_parts = explode('@', $lookup_username);
    $local_username = $lookup_username_parts[0];
    
    // Try different lookup endpoints
    $lookup_urls = [
        "https://$domain/api/v1/accounts/lookup?acct=" . urlencode($lookup_username), // Standard
        "https://$domain/users/" . urlencode($local_username) . ".json", // Akkoma alternative
    ];
    
    $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;
    $user_acct = $lookup_username; // Default to the full username we already have
    
    if ($account_data) {
        if (isset($account_data['id'])) {
            $user_id = $account_data['id'];
        }
        // Get the proper account identifier
        if (isset($account_data['acct'])) {
            $acct = $account_data['acct'];
            // Check if the acct already contains a domain
            if (strpos($acct, '@') === false) {
                // If not, add the domain
                $user_acct = $acct . '@' . $domain;
            } else {
                $user_acct = $acct;
            }
        }
    }
    
    $latest_post_url = null;
    $created_at = null;
    
    // If we couldn't get user ID through lookup, try to get statuses directly
    if (!$user_id) {
        // Try different statuses endpoints
        $statuses_urls = [
            "https://$domain/users/$local_username/outbox?page=true&limit=1", // ActivityPub
            "https://$domain/api/v1/accounts/$local_username/statuses?limit=1", // Mastodon API
            "https://$domain/@$local_username.json?limit=1", // Alternative
        ];
        
        $statuses = null;
        foreach ($statuses_urls as $statuses_url) {
            $response = @file_get_contents($statuses_url, false, $context);
            if ($response !== false) {
                $data = json_decode($response, true);
                
                // Handle different response formats
                if (isset($data['orderedItems'])) {
                    // ActivityPub format
                    if (!empty($data['orderedItems']) && isset($data['orderedItems'][0]['published'])) {
                        $created_at = $data['orderedItems'][0]['published'];
                        if (isset($data['orderedItems'][0]['id'])) {
                            $latest_post_url = $data['orderedItems'][0]['id'];
                        }
                        $statuses = [['created_at' => $created_at]];
                        break;
                    }
                } else if (is_array($data) && !empty($data) && isset($data[0]['created_at'])) {
                    // Standard API format
                    $statuses = $data;
                    $created_at = $data[0]['created_at'];
                    if (isset($data[0]['url'])) {
                        $latest_post_url = $data[0]['url'];
                    }
                    break;
                }
            }
        }
        
        if (!$statuses || empty($statuses)) {
            die("No posts found for the user.");
        }
    } else {
        // Get statuses using the 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) {
            die("Error fetching user's latest post.");
        }
        
        $statuses = json_decode($response, true);
        if (empty($statuses)) {
            die("No posts found for the user.");
        }
        
        $created_at = $statuses[0]['created_at'];
        if (isset($statuses[0]['url'])) {
            $latest_post_url = $statuses[0]['url'];
        }
    }
    
    // If we don't have a post URL, try to construct one
    if (!$latest_post_url && isset($statuses[0]['id'])) {
        $post_id = $statuses[0]['id'];
        $latest_post_url = "https://$domain/@$user_acct/$post_id";
    }
    
    // Format the date to yyyymmdd
    $date = date('Ymd', strtotime($created_at));

    // Prepare the data for saving to the JSON file
    $entry = [
        'username' => "@$user_acct",
        'date' => $date,
        'post_url' => $latest_post_url
    ];

    // Load the existing JSON data
    $filename = 'fedimissing.json';
    $json_data = [];
    if (file_exists($filename)) {
        $json_content = file_get_contents($filename);
        if ($json_content !== false) {
            $json_data = json_decode($json_content, true);
        }
        if (!is_array($json_data)) {
            $json_data = [];
        }
    }

    // Check if the user already exists
    $user_exists = false;
    foreach ($json_data as $existing_entry) {
        if ($existing_entry['username'] === "@$user_acct") {
            $user_exists = true;
            break;
        }
    }
    
    if ($user_exists) {
        die("User @$user_acct already exists in the JSON file.");
    }

    // Prepend the new entry to the array
    array_unshift($json_data, $entry);

    // Save the updated data back to the JSON file
    if (file_put_contents($filename, json_encode($json_data, JSON_PRETTY_PRINT))) {
        echo "Latest post date saved successfully: @$user_acct $date";
        if ($latest_post_url) {
            echo "<br>Post URL: <a href='$latest_post_url' target='_blank'>$latest_post_url</a>";
        }
    } else {
        echo "Error saving to JSON file. Please check file permissions.";
    }
} else {
    // Display the HTML form
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Fediverse Post Fetcher</title>
        <style>
            body { font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; }
            form { margin-top: 20px; }
            input[type="text"] { width: 100%; padding: 8px; margin: 8px 0; }
            button { padding: 10px 20px; background-color: #4CAF50; color: white; border: none; cursor: pointer; }
            button:hover { background-color: #45a049; }
            .error { color: red; }
            .success { color: green; }
        </style>
    </head>
    <body>
        <p>File new Missing User Report</p>
        <form action="" method="POST">
            <label for="fediverse_url">Enter Fediverse URL:</label>
            <input type="text" id="fediverse_url" name="fediverse_url" placeholder="e.g., https://mastodon.social/@user or https://example.com/notice/ABC123" required>
            <button type="submit">Get Newest Post Date</button>
        </form>
        <p>Supported formats:
            <ul>
                <li>https://mastodon.social/@username</li>
                <li>https://instance.tld/@username/1234567890 (any post URL)</li>
                <li>https://instance.tld/notice/ABC123 (Pleroma/Akkoma)</li>
                <li>https://instance.tld/objects/ABC123 (Akkoma)</li>
                <li>https://instance.tld/users/username (Akkoma)</li>
            </ul>
        </p>
        <p class="error">Note: Some instances may have API limitations or require authentication.</p>
    </body>
    </html>
    <?php
}
?>
