<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Encryption Utility
 *
 * Handles encryption and decryption of sensitive data
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/includes
 */

class Kitsune_AI_Platform_Encryption {

    /**
     * Get encryption key derived from WordPress salts
     *
     * @return string 32-byte key for AES-256
     */
    private static function get_encryption_key() {
        // Use WordPress SECURE_AUTH_KEY and SALT if available, otherwise fall back to hash of site URL
        $key_source = defined('SECURE_AUTH_KEY') ? SECURE_AUTH_KEY : '';
        $salt_source = defined('SECURE_AUTH_SALT') ? SECURE_AUTH_SALT : '';
        
        if (empty($key_source)) {
            $key_source = get_site_url();
        }

        return hash('sha256', $key_source . $salt_source, true);
    }

    /**
     * Encrypt plaintext
     *
     * @param string $plaintext Data to encrypt
     * @return string Base64 encoded string containing IV and encrypted data
     */
    public static function encrypt($plaintext) {
        if (empty($plaintext)) {
            return '';
        }

        try {
            $key = self::get_encryption_key();
            $iv_length = openssl_cipher_iv_length('AES-256-CBC');
            $iv = openssl_random_pseudo_bytes($iv_length);
            
            $encrypted = openssl_encrypt($plaintext, 'AES-256-CBC', $key, 0, $iv);
            
            if ($encrypted === false) {
                return '';
            }

            return base64_encode($iv . $encrypted);
        } catch (Exception $e) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('AI Platform Encryption Error: ' . $e->getMessage());
            }
            return '';
        }
    }

    /**
     * Decrypt ciphertext
     *
     * @param string $ciphertext Base64 encoded string containing IV and encrypted data
     * @return string Decrypted plaintext
     */
    public static function decrypt($ciphertext) {
        if (empty($ciphertext)) {
            return '';
        }

        try {
            $key = self::get_encryption_key();
            $data = base64_decode($ciphertext);
            
            $iv_length = openssl_cipher_iv_length('AES-256-CBC');
            
            if (strlen($data) <= $iv_length) {
                return '';
            }

            $iv = substr($data, 0, $iv_length);
            $encrypted = substr($data, $iv_length);
            
            $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $key, 0, $iv);
            
            return $decrypted !== false ? $decrypted : '';
        } catch (Exception $e) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('AI Platform Decryption Error: ' . $e->getMessage());
            }
            return '';
        }
    }
}
