<?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 {
  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'] ?? ''), '/');

function respond(int $code, array $payload): never {
  http_response_code($code);
  echo json_encode($payload, JSON_UNESCAPED_SLASHES);
  exit;
}
function env_value(string $env, string $key): string {
  if (preg_match('/^' . preg_quote($key, '/') . '=(.*)$/m', $env, $m)) return trim($m[1]);
  return '';
}

$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';
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']);
}

$wpFile = $tenantDir . '/data/wp.json';
if (is_file($wpFile)) @unlink($wpFile);

respond(200, ['ok' => true, 'wp_connected' => false]);
