<?php
declare(strict_types=1);

function fxh_require_license(PDO $pdo, $unused = null)
{
    $license = '';

    // 1) Standard PHP header
    if (function_exists('getallheaders')) {
        $h = getallheaders();
        if (!empty($h['X-FXH-LICENSE'])) {
            $license = trim($h['X-FXH-LICENSE']);
        }
    }

    // 2) PHP-FPM / Apache fallback
    if ($license === '' && isset($_SERVER['HTTP_X_FXH_LICENSE'])) {
        $license = trim($_SERVER['HTTP_X_FXH_LICENSE']);
    }

    // 3) Apache SetEnvIf fallback
    if ($license === '' && isset($_SERVER['FXH_LICENSE'])) {
        $license = trim($_SERVER['FXH_LICENSE']);
    }

    if ($license === '') {
        http_response_code(401);
        echo json_encode([
            "error" => "License not set",
            "source" => "header_missing"
        ]);
        exit;
    }

    $q = $pdo->prepare("
        SELECT license_key, active, expires_at
        FROM fxh_licenses
        WHERE license_key = ?
        LIMIT 1
    ");
    $q->execute([$license]);
    $row = $q->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        http_response_code(403);
        echo json_encode(["error" => "License invalid"]);
        exit;
    }

    if ((int)$row['active'] !== 1) {
        http_response_code(403);
        echo json_encode(["error" => "License inactive"]);
        exit;
    }

    if (!empty($row['expires_at']) && strtotime($row['expires_at']) < time()) {
        http_response_code(403);
        echo json_encode(["error" => "License expired"]);
        exit;
    }

    return $row;
}