<?php

if (!function_exists('MasterDecrypt')) {
    function MasterDecrypt($encryptedText)
    {
        if ($encryptedText == "") {
            return null;
        }

        // Key should be 32 bytes for AES-256
        $key = MASTER_ENCRYPTION_KEY; // 32 chars, 256 bits
        $method = 'aes-256-cbc'; // AES-256-CBC encryption method

        // Decode the base64-encoded data
        $decodedCombo = base64_decode($encryptedText);

        // Extract the IV and the encrypted text
        $iv = substr($decodedCombo, 0, 16); // IV length is 16 bytes
        $encryptedText = substr($decodedCombo, 16);

        // Decrypt the encrypted text
        $decryptedText = openssl_decrypt(base64_decode($encryptedText), $method, $key, OPENSSL_RAW_DATA, $iv);

        return $decryptedText;
    }
}

if (!function_exists('MasterEncrypt')) {
    function MasterEncrypt($input)
    {
        if ($input == "") {
            return null;
        }

        // Convert arrays or objects to JSON
        $text = is_array($input) || is_object($input) ? json_encode($input) : (string)$input;

        // Key should be 32 bytes for AES-256
        $key = MASTER_ENCRYPTION_KEY; // 32 chars, 256 bits
        $method = 'aes-256-cbc'; // AES-256-CBC encryption method

        // Generate a secure IV
        $iv = generateRandomString();

        // Encrypt the plaintext
        $enctext = openssl_encrypt($text, $method, $key, OPENSSL_RAW_DATA, $iv);

        // Combine IV and encrypted text
        $comboenc = base64_encode($iv . base64_encode($enctext));

        // Return the encoded data
        return $comboenc;
    }
}

if (!function_exists('generateRandomString')) {
    function generateRandomString($length = 16)
    {
        // Use random_bytes for a more secure IV
        return substr(bin2hex(random_bytes($length / 2)), 0, $length);
    }
}
