<?php
declare(strict_types=1);

$cfg = require __DIR__ . '/../config.php';
require __DIR__ . '/../lib/wp_common.php';

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

$raw = (string)(file_get_contents('php://input') ?: '');
$in  = $raw !== '' ? json_decode($raw, true) : [];
if ($raw !== '' && !is_array($in)) json_out(400, ['ok'=>false,'error'=>'Invalid JSON']);

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

[$paths, $active, $env] = require_active_and_license($cfg, $ref, $license);

$wp = read_json_file($paths['wpJson']);
$connected = is_array($wp) && ($wp['wp_url'] ?? '') !== '' && ($wp['wp_user'] ?? '') !== '' && is_array($wp['app_pass_enc'] ?? null);

json_out(200, [
  'ok' => true,
  'wp_connected' => $connected,
  'wp_url' => $connected ? (string)$wp['wp_url'] : '',
  'wp_user' => $connected ? (string)$wp['wp_user'] : '',
]);
