<?php
/**
 * license-php/api/public-key.php
 * GET /api/license/public-key
 */

require_once __DIR__ . '/../lib/Response.php';
Response::handleCors();

$config = require __DIR__ . '/../config/config.php';

$pubKeyPath = $config['keys']['public'] ?? '';
$publicKeyPem = '';

if ($pubKeyPath && file_exists($pubKeyPath)) {
    $publicKeyPem = file_get_contents($pubKeyPath);
} else {
    // Attempt derivation from private key
    $privKeyPath = $config['keys']['private'] ?? '';
    if ($privKeyPath && file_exists($privKeyPath)) {
        $privKey = openssl_pkey_get_private(file_get_contents($privKeyPath));
        if ($privKey) {
            $details = openssl_pkey_get_details($privKey);
            $publicKeyPem = $details['key'] ?? '';
        }
    }
}

if (!$publicKeyPem) {
    Response::json(500, [
        'success' => false,
        'message' => 'Public key is not configured or unavailable.'
    ]);
}

Response::json(200, [
    'success' => true,
    'public_key' => $publicKeyPem,
    'product' => $config['product_name']
]);
