<?php
declare(strict_types=1);
/**
 * Nuclear Fancy Pants Edition™ — NUCLEAR+++
 * File: includes/security.php
 * Last Edited: 2026-02-27
 * Description: Encryption helpers using sodium for API keys
 */
if (!defined('ABSPATH')) {
    exit('No direct script access allowed.');
}

if (!function_exists('amai_encrypt_key')) {
    function amai_encrypt_key($plain_text) {
        if (!extension_loaded('sodium') || !defined('AMAI_MASTER_KEY')) {
            error_log('AMAI: Sodium or master key missing - storing plain text');
            return $plain_text; // fallback
        }

        $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
        $ciphertext = sodium_crypto_secretbox($plain_text, $nonce, AMAI_MASTER_KEY);
        return base64_encode($nonce . $ciphertext);
    }
}

if (!function_exists('amai_decrypt_key')) {
    function amai_decrypt_key($ciphertext) {
        if (!extension_loaded('sodium') || !defined('AMAI_MASTER_KEY')) {
            error_log('AMAI: Sodium or master key missing - returning plain text');
            return $ciphertext; // fallback
        }

        $decoded = base64_decode($ciphertext);
        if ($decoded === false || strlen($decoded) < SODIUM_CRYPTO_SECRETBOX_NONCEBYTES) {
            return false;
        }

        $nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
        $cipher = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');

        $plain_text = sodium_crypto_secretbox_open($cipher, $nonce, AMAI_MASTER_KEY);
        if ($plain_text === false) {
            error_log('AMAI: Decryption failed - wrong key or corrupted data');
            return false;
        }

        return $plain_text;
    }
}