<?php
/**
 * Simple Encryption Handler
 *
 * @package PackshotPhotoAI
 */

namespace PackshotPhotoAI\Core;

defined('ABSPATH') || exit;

/**
 * Handles sensitive data encryption
 */
class Encryption {

    /**
     * Cipher method
     */
    private const CIPHER = 'AES-256-CBC';

    /**
     * Get encryption key derived from WP Salt
     *
     * @return string
     */
    private static function get_key(): string {
        $auth_key = defined('AUTH_KEY') ? AUTH_KEY : '';
        $secure_salt = defined('SECURE_AUTH_SALT') ? SECURE_AUTH_SALT : '';
        if (empty($auth_key)) {
            Logger::error('Encryption: AUTH_KEY is not defined. Encryption integrity is compromised.');
            $auth_key = wp_generate_password(64, true, true);
        }
        return hash('sha256', $auth_key . $secure_salt);
    }

    /**
     * Encrypt data
     *
     * @param string $data Plaintext
     * @return string Encrypted (base64)
     */
    public static function encrypt(string $data): string {
        if (empty($data)) return '';

        $key = self::get_key();
        $iv_length = openssl_cipher_iv_length(self::CIPHER);
        $iv = openssl_random_pseudo_bytes($iv_length);
        
        $encrypted = openssl_encrypt($data, self::CIPHER, $key, 0, $iv);
        
        // Return IV + Encrypted data
        return base64_encode($iv . $encrypted);
    }

    /**
     * Decrypt data
     *
     * @param string $data Encrypted base64
     * @return string Original plaintext
     */
    public static function decrypt(string $data): string {
        if (empty($data)) return '';

        $data = base64_decode($data);
        $key = self::get_key();
        $iv_length = openssl_cipher_iv_length(self::CIPHER);
        
        $iv = substr($data, 0, $iv_length);
        $encrypted = substr($data, $iv_length);
        
        if (strlen($iv) < $iv_length) return '';

        $decrypted = openssl_decrypt($encrypted, self::CIPHER, $key, 0, $iv);
        return $decrypted ?: '';
    }

    /**
     * Check if string is likely encrypted
     *
     * @param string $data
     * @return bool
     */
    public static function is_encrypted(string $data): bool {
        if (empty($data)) return false;
        
        // Very basic check: Is it likely encrypted/base64?
        // Encrypted data with IV for AES-256-CBC will be at least 16 (IV) + 16 (min block) bytes.
        // Base64 would be ~44 chars.
        if (strlen($data) < 32) return false;

        // Try to decrypt. If it returns something similar to what we expect, it was encrypted.
        // Actually, for API keys, we can just check if it fails decryption.
        $decrypted = self::decrypt($data);
        return !empty($decrypted) && $decrypted !== $data;
    }
}
