<?php
declare(strict_types=1);

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

// Load DB constants (your production file)
require_once "/var/www/html/config.database.php";

// Load license auth (we will make it backwards-compatible below)
require_once "/var/www/html/portal/api/_auth_license.php";

function fxh_optimizer_pdo(): PDO {
    // Your config.database.php must define these constants:
    // FXH_DB_HOST, FXH_DB_USER, FXH_DB_PASS, FXH_DB_NAME

    if (!defined("FXH_DB_HOST") || !defined("FXH_DB_USER") || !defined("FXH_DB_PASS") || !defined("FXH_DB_NAME")) {
        http_response_code(500);
        echo json_encode(["error"=>"DB constants missing", "hint"=>"Define FXH_DB_HOST/USER/PASS/NAME in /var/www/html/config.database.php"]);
        exit;
    }

    $hostRaw = (string)FXH_DB_HOST;

    // PRODUCTION HARDENING:
    // If someone accidentally pasted MySQL CLI host label like "127.0.0.1 via TCP/IP", fix it safely.
    $host = trim(explode(" ", $hostRaw)[0]);
    if ($host === "") $host = "127.0.0.1";

    $user = (string)FXH_DB_USER;
    $pass = (string)FXH_DB_PASS;
    $db   = (string)FXH_DB_NAME;

    $dsn = "mysql:host={$host};dbname={$db};charset=utf8mb4";

    $pdo = new PDO($dsn, $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);

    return $pdo;
}

function fxh_optimizer_require_license(PDO $pdo): array {
    // Backwards compatible auth helper
    return fxh_require_license($pdo);
}

function fxh_json_input(): array {
    $raw = file_get_contents("php://input");
    if ($raw === false || trim($raw) === "") return [];
    $j = json_decode($raw, true);
    if (!is_array($j)) {
        http_response_code(400);
        echo json_encode(["error"=>"Invalid JSON"]);
        exit;
    }
    return $j;
}

function fxh_send($code, $payload): void {
    http_response_code($code);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
}
