<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

$cfg = require __DIR__ . '/../config.php';
$tenantsDir = rtrim((string)($cfg['tenants_dir'] ?? ''), '/');
$keyFile    = (string)($cfg['wp_master_key_b64'] ?? '');
$allowed    = (array)($cfg['cors_allowed_origins'] ?? []);

/* ---------- helpers ---------- */
function respond(int $code, array $payload): never {
  http_response_code($code);
  echo json_encode($payload, JSON_UNESCAPED_SLASHES);
  exit;
}

function cors(array $allowed): void {
  $origin = (string)($_SERVER['HTTP_ORIGIN'] ?? '');
  if ($origin !== '' && in_array($origin, $allowed, true)) {
    header('Access-Control-Allow-Origin: ' . $origin);
    header('Vary: Origin');
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Allow-Headers: Content-Type');
    header('Access-Control-Allow-Methods: POST, OPTIONS');
  }
  if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
    http_response_code(204);
    exit;
  }
}

function read_json(string $p): ?array {
  if (!is_file($p)) return null;
  $raw = file_get_contents($p);
  $d = json_decode((string)$raw, true);
  return is_array($d) ? $d : null;
}

function master_key(string $keyFile): string {
  if (!is_file($keyFile)) {
    @mkdir(dirname($keyFile), 0750, true);
    $b64 = base64_encode(random_bytes(32));
    file_put_contents($keyFile, $b64, LOCK_EX);
    @chmod($keyFile, 0640);
  }
  $b64 = trim((string)file_get_contents($keyFile));
  $key = base64_decode($b64, true);
  if (!is_string($key) || strlen($key) !== 32) {
    throw new RuntimeException('Invalid wp master key file');
  }
  return $key;
}

function decrypt_value(string $encB64, string $ivB64, string $key): string {
  $ct = base64_decode($encB64, true);
  $iv = base64_decode($ivB64, true);
  if (!is_string($ct) || !is_string($iv) || strlen($iv) !== 16) {
    throw new RuntimeException('Bad encrypted payload');
  }
  $pt = openssl_decrypt($ct, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
  if (!is_string($pt) || $pt === '') {
    throw new RuntimeException('Decrypt failed');
  }
  return $pt;
}

function wp_post_create(string $wpUrl, string $wpUser, string $wpAppPass, array $post): array {
  $wpUrl = rtrim($wpUrl, '/');
  $endpoint = $wpUrl . '/wp-json/wp/v2/posts';

  $ch = curl_init($endpoint);
  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
      'Content-Type: application/json',
      'Accept: application/json',
      'Authorization: Basic ' . base64_encode($wpUser . ':' . $wpAppPass),
    ],
    CURLOPT_POSTFIELDS => json_encode($post, JSON_UNESCAPED_SLASHES),
    CURLOPT_TIMEOUT => 25,
  ]);

  $body = curl_exec($ch);
  $err  = curl_error($ch);
  $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);

  if ($body === false) {
    return ['ok' => false, 'http' => 0, 'error' => $err ?: 'curl_failed', 'body' => ''];
  }

  return ['ok' => ($code >= 200 && $code < 300), 'http' => $code, 'error' => '', 'body' => (string)$body];
}

cors($allowed);

/* ---------- request ---------- */
$body = json_decode(file_get_contents('php://input') ?: '', true);
if (!is_array($body)) respond(400, ['ok' => false, 'error' => 'Invalid JSON']);

$ref     = trim((string)($body['ref'] ?? ''));
$license = trim((string)($body['license'] ?? ''));

if (!preg_match('/^t_[a-f0-9]{16}$/', $ref)) respond(400, ['ok' => false, 'error' => 'Invalid tenant_ref']);
if ($license === '') respond(400, ['ok' => false, 'error' => 'Missing license']);

$tenantDir = $tenantsDir . '/' . $ref;
$envPath   = $tenantDir . '/.env';
$wpPath    = $tenantDir . '/data/wp.json';

if (!is_file($envPath) || !is_file($wpPath)) respond(404, ['ok' => false, 'error' => 'Tenant not connected']);

$env = (string)(file_get_contents($envPath) ?: '');
if (!preg_match('/^LICENSE_KEY=(.+)$/m', $env, $m) || trim($m[1]) !== $license) {
  respond(403, ['ok' => false, 'error' => 'License mismatch']);
}

$wp = read_json($wpPath);
if (!is_array($wp)) respond(500, ['ok' => false, 'error' => 'Corrupt wp.json']);

$wpUrl  = trim((string)($wp['wp_url'] ?? ''));
$wpUser = trim((string)($wp['wp_user'] ?? ''));
$enc    = trim((string)($wp['app_pass_enc'] ?? ''));
$iv     = trim((string)($wp['iv'] ?? ''));

if ($wpUrl === '' || $wpUser === '' || $enc === '' || $iv === '') {
  respond(400, ['ok' => false, 'error' => 'Missing WP connection fields']);
}

try {
  $key = master_key($keyFile);
  $wpPass = decrypt_value($enc, $iv, $key);
} catch (Throwable $e) {
  respond(500, ['ok' => false, 'error' => 'Decrypt error: ' . $e->getMessage()]);
}

$title = 'MY.TOWN Blogger Kit Test Draft';
$content = 'If you can see this draft in WordPress, your connection works.';

$res = wp_post_create($wpUrl, $wpUser, $wpPass, [
  'title' => $title,
  'content' => $content,
  'status' => 'draft',
]);

if (!$res['ok']) {
  respond(200, [
    'ok' => false,
    'error' => 'WordPress returned HTTP ' . $res['http'],
    'wp_body' => substr($res['body'], 0, 800),
  ]);
}

$decoded = json_decode($res['body'], true);
if (!is_array($decoded)) {
  respond(200, [
    'ok' => false,
    'error' => 'WordPress returned non-JSON body',
    'wp_body' => substr($res['body'], 0, 800),
  ]);
}

$postId = (int)($decoded['id'] ?? 0);
$link   = (string)($decoded['link'] ?? '');

$wpBase = rtrim($wpUrl, '/');
$editUrl = ($postId > 0) ? ($wpBase . '/wp-admin/post.php?post=' . $postId . '&action=edit') : '';
$previewUrl = ($postId > 0) ? ($wpBase . '/?p=' . $postId . '&preview=true') : '';

if ($link === '' && $previewUrl !== '') $link = $previewUrl;

respond(200, [
  'ok' => true,
  'post_id' => $postId,
  'link' => $link,
  'edit_url' => $editUrl,
  'preview_url' => $previewUrl,
]);
