<?php
// Test script to verify secure key storage
echo "Testing Secure Encryption Key Storage\n";
echo "======================================\n\n";

// Test 1: Include the API and check if key is loaded
require_once('api.php');

echo "Test 1: Key loaded from PHP file\n";
if (defined('ENCRYPTION_MASTER_KEY_RUNTIME')) {
    echo "  ✓ ENCRYPTION_MASTER_KEY_RUNTIME is defined\n";
    echo "  ✓ Key length: " . strlen(ENCRYPTION_MASTER_KEY_RUNTIME) . " characters\n";
    echo "  ✓ Key preview: " . substr(ENCRYPTION_MASTER_KEY_RUNTIME, 0, 16) . "...\n";
} else {
    echo "  ✗ FAILED: Key constant not defined\n";
}
echo "\n";

// Test 2: Check if generateDailyKey() returns the key
echo "Test 2: generateDailyKey() function\n";
$key = generateDailyKey(null);
if (!empty($key) && strlen($key) == 64) {
    echo "  ✓ Function returns valid key\n";
    echo "  ✓ Key matches runtime constant: " . ($key === ENCRYPTION_MASTER_KEY_RUNTIME ? 'YES' : 'NO') . "\n";
} else {
    echo "  ✗ FAILED: Invalid key returned\n";
}
echo "\n";

// Test 3: Verify the key file was updated with actual key
echo "Test 3: Verify key file contents\n";
$keyFileContent = file_get_contents('data/encryption_key.php');
if (strpos($keyFileContent, "define('ENCRYPTION_MASTER_KEY', '');") !== false) {
    echo "  ⚠ WARNING: Key file still has empty key - will be generated on first use\n";
} elseif (preg_match("/define\('ENCRYPTION_MASTER_KEY',\s*'([a-f0-9]{64})'\);/", $keyFileContent, $matches)) {
    echo "  ✓ Key file contains generated key\n";
    echo "  ✓ Key in file matches runtime: " . ($matches[1] === ENCRYPTION_MASTER_KEY_RUNTIME ? 'YES' : 'NO') . "\n";
} else {
    echo "  ✗ FAILED: Could not find valid key in file\n";
}
echo "\n";

// Test 4: Test encryption/decryption with the key
echo "Test 4: Encryption/Decryption test\n";
$testData = json_encode(['test' => 'data', 'value' => 12345]);
$encrypted = encryptData($testData, $key);
$decrypted = safeDecryptData($encrypted, $key);
$decryptedJson = json_decode($decrypted, true);

if ($decryptedJson && $decryptedJson['test'] === 'data') {
    echo "  ✓ Encryption/Decryption works correctly\n";
} else {
    echo "  ✗ FAILED: Encryption/Decryption failed\n";
}
echo "\n";

echo "All tests complete!\n";
echo "\nSecurity Notes:\n";
echo "- The master key is stored in: data/encryption_key.php\n";
echo "- .htaccess denies direct web access to this file\n";
echo "- The key can only be accessed by PHP code on the server\n";
?>
