<?php
declare(strict_types=1);

$root = dirname(__DIR__);
require_once $root . '/db_bootstrap.php';
require_once $root . '/ui_settings.php';

ensure_db(true);
$conn = $GLOBALS['conn'] ?? null;
if (!($conn instanceof mysqli)) throw new RuntimeException('Database connection is unavailable.');
ua_ensure_settings_table($conn);

function theme_scope_assert(bool $condition, string $message): void
{
    if (!$condition) throw new RuntimeException($message);
}

function theme_scope_delete(mysqli $conn, string $key): void
{
    $schema = ua_app_settings_schema($conn);
    $column = $schema === 'setting_key' ? 'setting_key' : 'key';
    $stmt = $conn->prepare("DELETE FROM app_settings WHERE `{$column}`=?");
    if (!$stmt) return;
    $stmt->bind_param('s', $key);
    $stmt->execute();
    $stmt->close();
}

$previousOverride = $GLOBALS['UA_INSTALL_CONFIG_OVERRIDE'] ?? null;
$suffix = bin2hex(random_bytes(6));
$legacyTheme = ua_get_setting($conn, 'ui_theme', null);
$branchKey = '';
$agentKey = '';

try {
    $GLOBALS['UA_INSTALL_CONFIG_OVERRIDE'] = [
        'install_type' => 'branch',
        'link' => ['instance_id' => 'theme-scope-branch-' . $suffix],
    ];
    $branchKey = ua_ui_setting_storage_key('ui_theme');
    ua_set_ui_setting($conn, 'ui_theme', 'dark_blue');

    $GLOBALS['UA_INSTALL_CONFIG_OVERRIDE'] = [
        'install_type' => 'agent',
        'link' => ['instance_id' => 'theme-scope-agent-' . $suffix],
    ];
    $agentKey = ua_ui_setting_storage_key('ui_theme');
    ua_set_ui_setting($conn, 'ui_theme', 'light_clean');

    theme_scope_assert($branchKey !== $agentKey, 'Installation scopes produced the same key.');

    $GLOBALS['UA_INSTALL_CONFIG_OVERRIDE'] = [
        'install_type' => 'branch',
        'link' => ['instance_id' => 'theme-scope-branch-' . $suffix],
    ];
    theme_scope_assert(ua_get_ui_setting($conn, 'ui_theme', '') === 'dark_blue', 'Branch theme was not retained.');

    $GLOBALS['UA_INSTALL_CONFIG_OVERRIDE'] = [
        'install_type' => 'agent',
        'link' => ['instance_id' => 'theme-scope-agent-' . $suffix],
    ];
    theme_scope_assert(ua_get_ui_setting($conn, 'ui_theme', '') === 'light_clean', 'Agent theme was not retained.');
    theme_scope_assert(ua_get_setting($conn, 'ui_theme', null) === $legacyTheme, 'Scoped writes changed the legacy/global theme.');
} finally {
    if ($branchKey !== '') theme_scope_delete($conn, $branchKey);
    if ($agentKey !== '') theme_scope_delete($conn, $agentKey);
    if ($previousOverride === null) unset($GLOBALS['UA_INSTALL_CONFIG_OVERRIDE']);
    else $GLOBALS['UA_INSTALL_CONFIG_OVERRIDE'] = $previousOverride;
}

echo "theme_instance_scope_test: OK\n";
