<?php
/**
 * Dakidarts Numerology Core - Helpers
 *
 * Utility functions for encryption, sanitization, and logging.
 *
 * @package Dakidarts_Numerology_Core
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if ( ! class_exists( 'Dakidarts_Helpers' ) ) {

    class Dakidarts_Helpers {

        /**
         * Encrypt a string using AES-256-CBC
         *
         * @param string $data Plain text to encrypt.
         * @param string $key  Secret key.
         * @return string Base64 encoded encrypted string.
         */
        public static function encrypt( $data, $key ) {
            $key       = hash( 'sha256', $key, true );
            $iv        = openssl_random_pseudo_bytes( 16 );
            $encrypted = openssl_encrypt( $data, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv );
            return base64_encode( $iv . $encrypted );
        }

        /**
         * Decrypt a string encrypted with AES-256-CBC
         *
         * @param string $data Base64 encoded encrypted string.
         * @param string $key  Secret key.
         * @return string|false Decrypted plain text or false on failure.
         */
        public static function decrypt( $data, $key ) {
            $data = base64_decode( $data );
            if ( strlen( $data ) < 16 ) {
                return false;
            }

            $key = hash( 'sha256', $key, true );
            $iv  = substr( $data, 0, 16 );
            $encrypted = substr( $data, 16 );

            return openssl_decrypt( $encrypted, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv );
        }

        /**
         * Sanitize all input data recursively
         *
         * @param mixed $data Input data (array|string)
         * @return mixed Sanitized data
         */
        public static function sanitize_input( $data ) {
            if ( is_array( $data ) ) {
                return array_map( [ __CLASS__, 'sanitize_input' ], $data );
            }
            return sanitize_text_field( wp_unslash( $data ) );
        }

    }
}
