<?php
header('Content-Type: text/plain');

// Get query parameters
$instanceUrl = $_GET['instanceurl'] ?? '';
$apiKey = $_GET['apikey'] ?? '';
$oldPostUrl = $_GET['oldposturl'] ?? '';

// Validate required parameters
if (empty($instanceUrl) || empty($apiKey)) {
    http_response_code(400);
    echo "Error: instanceurl and apikey parameters are required";
    exit;
}

// Load JSON data
$jsonFile = 'fedimissing.json';
if (!file_exists($jsonFile)) {
    http_response_code(404);
    echo "Error: fedimissing.json not found";
    exit;
}

$jsonData = file_get_contents($jsonFile);
$missingPersons = json_decode($jsonData, true);

if ($missingPersons === null) {
    http_response_code(500);
    echo "Error: Invalid JSON format";
    exit;
}

// Generate HTML content
$htmlContent = '<a href="https://alcea-wisteria.de/PHP/0demo/2024-03-07-FediTools/2025-09-10-FediIsMissing/">Missing Fedi person:</a> <a target="_blank" href="https://alcea-wisteria.de/PHP/0demo/2024-03-07-FediTools/2025-09-10-FediIsMissing/updatereport.php" style=color:blue>(update)</a><hr>';

foreach ($missingPersons as $person) {
    $username = htmlspecialchars($person['username']);
    $postUrl = htmlspecialchars($person['post_url']);
    $date = $person['date'];
    
    // Calculate days missing
    $today = new DateTime();
    $missingDate = DateTime::createFromFormat('Ymd', $date);
    
    if ($missingDate) {
        $interval = $today->diff($missingDate);
        $daysMissing = $interval->days;
        $daysText = $daysMissing == 1 ? 'day' : 'days';
    } else {
        $daysMissing = 'unknown';
        $daysText = 'days';
    }
    
    $htmlContent .= "<a href=\"$postUrl\">$username</a> - $daysMissing $daysText missing<br>";
}

// Prepare API request
$apiEndpoint = rtrim($instanceUrl, '/') . '/api/v1/statuses';

$postData = [
    'status' => $htmlContent,
    'content_type' => 'text/html',
    'visibility' => 'public'
];

// Headers for Akkoma API
$headers = [
    'Authorization: Bearer ' . $apiKey,
    'Content-Type: application/json'
];

// Initialize cURL
$ch = curl_init();

if (!empty($oldPostUrl)) {
    // Edit existing post - extract status ID from URL
    $urlParts = parse_url($oldPostUrl);
    $pathParts = explode('/', trim($urlParts['path'], '/'));
    $statusId = end($pathParts);
    
    curl_setopt_array($ch, [
        CURLOPT_URL => $apiEndpoint . '/' . $statusId,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => 'PUT',
        CURLOPT_POSTFIELDS => json_encode($postData),
        CURLOPT_HTTPHEADER => $headers
    ]);
    
    $action = "editing";
} else {
    // Create new post
    curl_setopt_array($ch, [
        CURLOPT_URL => $apiEndpoint,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($postData),
        CURLOPT_HTTPHEADER => $headers
    ]);
    
    $action = "posting";
}

// Execute API request
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if (curl_error($ch)) {
    http_response_code(500);
    echo "Error: cURL error - " . curl_error($ch);
    curl_close($ch);
    exit;
}

curl_close($ch);

// Handle response
if ($httpCode >= 200 && $httpCode < 300) {
    $responseData = json_decode($response, true);
    $postUrl = $responseData['url'] ?? $oldPostUrl;
    
    echo "Successfully $action post: " . $postUrl . "\n";
    echo "Generated content:\n\n";
    echo $htmlContent;
} else {
    http_response_code($httpCode);
    echo "Error: API returned status code $httpCode\n";
    echo "Response: " . $response;
}
?>
