<?php
declare(strict_types=1);

function env_load(string $path): array {
    if (!is_file($path)) return [];
    $lines = preg_split("/\r\n|\n|\r/", (string)file_get_contents($path)) ?: [];
    $out = [];
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, '#')) continue;
        $pos = strpos($line, '=');
        if ($pos === false) continue;
        $k = trim(substr($line, 0, $pos));
        $v = trim(substr($line, $pos + 1));
        $out[$k] = $v;
    }
    return $out;
}

function http_json(string $url, array $payload, array $headers): array {
    $body = json_encode($payload, JSON_UNESCAPED_SLASHES);
    if ($body === false) return [0, '', 'json_encode_failed'];

    // Prefer curl if available
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => array_merge($headers, ['Content-Type: application/json']),
            CURLOPT_POSTFIELDS => $body,
            CURLOPT_TIMEOUT => 30,
        ]);
        $res = curl_exec($ch);
        $err = curl_error($ch);
        $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return [$code, (string)$res, $err];
    }

    // Fallback: stream context
    $opts = [
        'http' => [
            'method' => 'POST',
            'header' => implode("\r\n", array_merge($headers, ['Content-Type: application/json'])),
            'content' => $body,
            'timeout' => 30,
            'ignore_errors' => true,
        ]
    ];
    $ctx = stream_context_create($opts);
    $res = @file_get_contents($url, false, $ctx);
    $code = 0;
    if (isset($http_response_header) && is_array($http_response_header)) {
        foreach ($http_response_header as $h) {
            if (preg_match('#^HTTP/\S+\s+(\d+)#', $h, $m)) { $code = (int)$m[1]; break; }
        }
    }
    return [$code, (string)$res, ''];
}

$root = __DIR__;
$envPath = $root . '/.env';
if (!is_file($envPath)) {
    // try one level up if someone copied env there
    $alt = dirname($root) . '/.env';
    if (is_file($alt)) $envPath = $alt;
}

$env = env_load($envPath);

$wpUrl = rtrim((string)($env['WP_URL'] ?? ''), '/');
$wpUser = (string)($env['WP_USER'] ?? '');
$wpPass = (string)($env['WP_APP_PASSWORD'] ?? '');

if ($wpUrl === '' || $wpUser === '' || $wpPass === '') {
    fwrite(STDERR, "ERROR: Missing WP_URL, WP_USER, or WP_APP_PASSWORD in .env\n");
    fwrite(STDERR, "Edit .env, then re-run this script.\n");
    exit(1);
}

$endpoint = $wpUrl . '/wp-json/wp/v2/posts';

$title = 'MY.TOWN Blogger Test Post';
$content = 'This is a test post created by the MY.TOWN Blogger install validation. If you see this, WordPress credentials are working.';

$auth = base64_encode($wpUser . ':' . $wpPass);
$headers = [
    'Authorization: Basic ' . $auth,
    'Accept: application/json',
];

[$code, $res, $err] = http_json($endpoint, [
    'title' => $title,
    'content' => $content,
    'status' => 'draft'
], $headers);

if ($err !== '') {
    fwrite(STDERR, "ERROR: HTTP request failed: {$err}\n");
    exit(1);
}

if ($code < 200 || $code >= 300) {
    fwrite(STDERR, "ERROR: WordPress returned HTTP {$code}\n");
    fwrite(STDERR, substr($res, 0, 500) . "\n");
    exit(1);
}

echo "OK: Posted draft successfully.\n";
echo "Response (first 300 chars):\n";
echo substr($res, 0, 300) . "\n";
exit(0);
