<?php
require_once __DIR__ . '/security.php';

if (defined('TENANT_URL') && !empty(TENANT_URL)) {
    $_REQUEST['tenant'] = TENANT_URL;
}

if (!defined('CONFIG_LOADED')) {
    $tenant = enrep_tenant_segment();
    if ($tenant !== '' && is_file('../../' . $tenant . '/config.php')) {
        require_once '../../' . $tenant . '/config.php';
    } elseif (is_file('/config.php')) {
        require_once '/config.php';
    }
}

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    http_response_code(500);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['ok' => false, 'error' => 'Tenant database unavailable']);
    exit;
}

enrep_require_admin();

function enrep_system_api_json(array $payload, int $status = 200): void
{
    if (!headers_sent()) {
        http_response_code($status);
        header('Content-Type: application/json; charset=utf-8');
        header('Cache-Control: no-store');
    }
    echo json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
    exit;
}

function enrep_system_api_random_key(): string
{
    return 'enrep_live_' . rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
}

function enrep_system_api_settings(): array
{
    $stmt = $GLOBALS['con']->prepare("SELECT `system_api_settings` FROM `system` WHERE `id`=1 LIMIT 1");
    if (!$stmt) {
        return [
            'ok' => false,
            'setup_required' => true,
            'error' => 'API key storage is not installed for this tenant.',
        ];
    }

    $stmt->execute();
    $result = $stmt->get_result();
    $row = mysqli_fetch_assoc($result);
    $stmt->close();

    $settings = json_decode((string)($row['system_api_settings'] ?? ''), true);
    if (!is_array($settings)) {
        $settings = [];
    }

    return [
        'ok' => true,
        'configured' => !empty($settings['key_hash']),
        'enabled' => !empty($settings['enabled']),
        'key_prefix' => (string)($settings['key_prefix'] ?? ''),
        'created_by' => (string)($settings['created_by'] ?? ''),
        'created_at' => (int)($settings['created_at'] ?? 0),
        'regenerated_at' => (int)($settings['regenerated_at'] ?? 0),
        'last_used_at' => (int)($settings['last_used_at'] ?? 0),
    ];
}

function enrep_system_api_save_settings(array $settings): bool
{
    $json = json_encode($settings, JSON_UNESCAPED_SLASHES);
    $stmt = $GLOBALS['con']->prepare("UPDATE `system` SET `system_api_settings`=? WHERE `id`=1");
    if (!$stmt) {
        return false;
    }

    $stmt->bind_param('s', $json);
    $ok = $stmt->execute();
    $stmt->close();
    return $ok;
}

$action = enrep_request_enum('action', ['status', 'generate', 'disable'], 'status');

if ($action === 'status') {
    enrep_system_api_json(enrep_system_api_settings());
}

if ($action === 'disable') {
    $current = enrep_system_api_settings();
    if (empty($current['ok'])) {
        enrep_system_api_json($current, 503);
    }

    $settings = [
        'enabled' => false,
        'key_prefix' => (string)($current['key_prefix'] ?? ''),
        'key_hash' => '',
        'created_by' => (string)($current['created_by'] ?? ''),
        'created_at' => (int)($current['created_at'] ?? 0),
        'regenerated_at' => time(),
        'last_used_at' => (int)($current['last_used_at'] ?? 0),
    ];

    if (!enrep_system_api_save_settings($settings)) {
        enrep_system_api_json(['ok' => false, 'setup_required' => true, 'error' => 'API key storage is not installed for this tenant.'], 503);
    }

    enrep_system_api_json(enrep_system_api_settings());
}

$apiKey = enrep_system_api_random_key();
$now = time();
$settings = [
    'enabled' => true,
    'key_prefix' => substr($apiKey, 0, 22),
    'key_hash' => hash('sha256', $apiKey),
    'created_by' => (string)($_SESSION['userid'] ?? $_SESSION['adminunique'] ?? ''),
    'created_at' => $now,
    'regenerated_at' => $now,
    'last_used_at' => 0,
];

if (!enrep_system_api_save_settings($settings)) {
    enrep_system_api_json(['ok' => false, 'setup_required' => true, 'error' => 'API key storage is not installed for this tenant.'], 503);
}

$status = enrep_system_api_settings();
$status['api_key'] = $apiKey;
$status['show_once'] = true;
enrep_system_api_json($status);
