<?php
/**
 * Security class for API key encryption and decryption
 */
class Nietos_AI_Security {

    /**
     * Encrypt API key
     */
    public function encrypt_api_key($key) {
        if (empty($key)) {
            return '';
        }

        $salt = $this->get_encryption_salt();
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
        $encrypted = openssl_encrypt($key, 'aes-256-cbc', $salt, 0, $iv);

        // Return base64 encoded IV + encrypted data
        return base64_encode($iv . $encrypted);
    }

    /**
     * Decrypt API key
     */
    public function decrypt_api_key($encrypted_key) {
        if (empty($encrypted_key)) {
            return '';
        }

        $salt = $this->get_encryption_salt();
        $data = base64_decode($encrypted_key);
        $iv_length = openssl_cipher_iv_length('aes-256-cbc');
        $iv = substr($data, 0, $iv_length);
        $encrypted = substr($data, $iv_length);

        return openssl_decrypt($encrypted, 'aes-256-cbc', $salt, 0, $iv);
    }

    /**
     * Get encryption salt from WordPress constants
     */
    private function get_encryption_salt() {
        if (defined('AUTH_KEY') && defined('SECURE_AUTH_KEY')) {
            return hash('sha256', AUTH_KEY . SECURE_AUTH_KEY);
        }

        // Fallback (not recommended, but prevents errors)
        return hash('sha256', 'nietos-ai-fallback-salt');
    }

    /**
     * Verify nonce for AJAX requests
     */
    public function verify_nonce($nonce) {
        return wp_verify_nonce($nonce, 'wp_rest');
    }

    /**
     * Check if current user has required capabilities
     */
    public function check_permissions() {
        return current_user_can('manage_options');
    }

    /**
     * Sanitize user input
     */
    public function sanitize_input($input) {
        if (is_array($input)) {
            return array_map(array($this, 'sanitize_input'), $input);
        }

        return sanitize_text_field($input);
    }
}
