<?php
declare(strict_types=1);

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

$cfg = require __DIR__ . '/../config.php';
$allowed = $cfg['cors_allowed_origins'] ?? ['https://blogger.mytown.ink'];
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

function cors(array $allowed, string $origin): void {
  // file:// pages send Origin: null in many browsers
  if ($origin === 'null' || $origin === '') {
    header('Access-Control-Allow-Origin: *');
  } elseif (in_array($origin, $allowed, true)) {
    header('Access-Control-Allow-Origin: ' . $origin);
    header('Vary: Origin');
  }
  header('Access-Control-Allow-Methods: POST, OPTIONS');
  header('Access-Control-Allow-Headers: Content-Type');
  header('Access-Control-Max-Age: 86400');
}

cors($allowed, $origin);

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
  http_response_code(204);
  exit;
}

$tenantsDir = rtrim((string)($cfg['tenants_dir'] ?? ''), '/');
$keyB64     = (string)($cfg['wp_master_key_b64'] ?? '');function respond(int $code, array $payload): never {
  http_response_code($code);
  echo json_encode($payload, JSON_UNESCAPED_SLASHES);
  exit;
}

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

function write_json_atomic(string $path, array $data): bool {
  $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
  if ($json === false) return false;
  $tmp = $path . '.tmp';
  if (file_put_contents($tmp, $json, LOCK_EX) === false) return false;
  @chmod($tmp, 0640);
  return @rename($tmp, $path);
}

function env_value(string $env, string $key): string {
  if (preg_match('/^' . preg_quote($key, '/') . '=(.*)$/m', $env, $m)) return trim($m[1]);
  return '';
}

function encrypt_value(string $plaintext, string $keyB64): array {
  $dir = dirname($keyB64);
  if (!is_dir($dir)) @mkdir($dir, 0750, true);

  if (!is_file($keyB64)) {
    @file_put_contents($keyB64, base64_encode(random_bytes(32)), LOCK_EX);
    @chmod($keyB64, 0640);
  }
  $keyRaw = (string)@file_get_contents($keyB64);
  $key = base64_decode(trim($keyRaw), true);
  if (!is_string($key) || strlen($key) !== 32) {
    throw new RuntimeException('Invalid master key');
  }

  $iv = random_bytes(16);
  $ciphertext = openssl_encrypt($plaintext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
  if ($ciphertext === false) throw new RuntimeException('Encrypt failed');

  return ['data' => base64_encode($ciphertext), 'iv' => base64_encode($iv)];
}

$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'] ?? ''));
$wpUrl   = trim((string)($body['wp_url'] ?? ''));
$wpUser  = trim((string)($body['wp_user'] ?? ''));
$wpPass  = trim((string)($body['wp_app_password'] ?? ''));

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

$tenantDir = $tenantsDir . '/' . $ref;
$envPath   = $tenantDir . '/.env';
if (!is_file($envPath)) respond(404, ['ok' => false, 'error' => 'Tenant not found']);

$env = (string)(file_get_contents($envPath) ?: '');
$expected = env_value($env, 'LICENSE_KEY');
if ($expected === '' || !hash_equals($expected, $license)) {
  respond(403, ['ok' => false, 'error' => 'License mismatch']);
}

try {
  $enc = encrypt_value($wpPass, $keyB64);
} catch (Throwable $e) {
  respond(500, ['ok' => false, 'error' => 'Encryption failed']);
}

$data = [
  'wp_url' => $wpUrl,
  'wp_user' => $wpUser,
  'app_pass_enc' => $enc['data'],
  'iv' => $enc['iv'],
  'connected_at' => date('c'),
];

if (!write_json_atomic($tenantDir . '/data/wp.json', $data)) {
  respond(500, ['ok' => false, 'error' => 'Failed to save']);
}

respond(200, [
  'ok' => true,
  'wp_connected' => true,
  'wp_url' => $wpUrl,
  'wp_user' => $wpUser,
]);
