<?php
// Standalone test script - doesn't include api.php to avoid action requirement
define('DATA_DIR', 'data');
define('ENCRYPTION_META_FILE', DATA_DIR . '/encryption_meta.json');

function loadEncryptionMeta() {
    if (file_exists(ENCRYPTION_META_FILE)) {
        $data = file_get_contents(ENCRYPTION_META_FILE);
        $meta = json_decode($data, true);
        return $meta;
    }
    return null;
}

function generateDailyKey() {
    $encryptionMeta = loadEncryptionMeta();
    if (isset($encryptionMeta['masterKey'])) {
        return $encryptionMeta['masterKey'];
    }
    return null;
}

function safeDecryptData($encryptedData, $key) {
    try {
        $decKey = substr(hash('sha256', $key, true), 0, 32);
        $data = base64_decode($encryptedData);
        if ($data === false || strlen($data) < 16) {
            return $encryptedData;
        }
        $iv = substr($data, 0, 16);
        $encrypted = substr($data, 16);
        $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $decKey, 0, $iv);
        if ($decrypted === false) {
            return $encryptedData;
        }
        return $decrypted;
    } catch (Exception $e) {
        return $encryptedData;
    }
}

echo "Testing Forum Data Decryption\n";
echo "=============================\n\n";

// Load encryption metadata
$meta = loadEncryptionMeta();
echo "Encryption Metadata:\n";
echo "  Last Encryption: " . $meta['lastEncryptionDate'] . "\n";
echo "  Is Encrypted: " . ($meta['isEncrypted'] ? 'Yes' : 'No') . "\n";
echo "  Master Key Present: " . (isset($meta['masterKey']) ? 'Yes' : 'No') . "\n";
echo "\n";

// Test decrypting users file
$usersFile = DATA_DIR . '/users.json.enc';
if (file_exists($usersFile)) {
    echo "Testing Users File Decryption:\n";
    $encryptedData = file_get_contents($usersFile);
    $masterKey = generateDailyKey();
    if ($masterKey) {
        $decrypted = safeDecryptData($encryptedData, $masterKey);
        $users = json_decode($decrypted, true);
        if ($users !== null) {
            echo "  SUCCESS: Decrypted " . count($users) . " users\n";
            if (count($users) > 0) {
                echo "  Sample user: " . $users[0]['username'] . "\n";
            }
        } else {
            echo "  FAILED: Could not parse JSON after decryption\n";
            echo "  First 100 chars: " . substr($decrypted, 0, 100) . "\n";
        }
    } else {
        echo "  ERROR: No master key found\n";
    }
} else {
    echo "Users file not found\n";
}

echo "\nTest complete!\n";
?>
