<?php

namespace Bricksforge\Api;

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

class Utils
{

    public function encrypt($string)
    {
        // If its an empty string, return it
        if (empty($string)) {
            return $string;
        }

        // If its already encrypted, return it
        if ($this->is_encrypted($string)) {
            return $string;
        }

        $method = 'aes-256-cbc';
        $secretKey = BRICKSFORGE_SECRET_KEY;
        $ivLength = openssl_cipher_iv_length($method);
        $iv = openssl_random_pseudo_bytes($ivLength);

        $encrypted_string = openssl_encrypt($string, $method, $secretKey, OPENSSL_RAW_DATA, $iv);
        $encrypted_string = base64_encode($encrypted_string . '::' . $iv);

        return $encrypted_string;
    }

    public function decrypt($encrypted_string)
    {
        // If its an empty string, return it
        if (empty($encrypted_string)) {
            return $encrypted_string;
        }

        // If its not encrypted, return it
        if (!$this->is_encrypted($encrypted_string)) {
            return $encrypted_string;
        }

        $method = 'aes-256-cbc';
        $secretKey = BRICKSFORGE_SECRET_KEY;

        $parts = explode('::', base64_decode($encrypted_string), 2);

        if (count($parts) < 2) {
            return;
        }

        list($encrypted_data, $iv) = $parts;

        $decrypted_string = openssl_decrypt($encrypted_data, $method, $secretKey, OPENSSL_RAW_DATA, $iv);

        return $decrypted_string;
    }

    public function is_encrypted($string)
    {
        // Check if string is base64 encoded first
        if (!is_string($string) || !preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) {
            return false;
        }

        // Try to base64 decode and check for separator
        $decoded = base64_decode($string, true);
        if ($decoded === false) {
            return false;
        }

        // Verify the decoded string contains the separator and has data on both sides
        $parts = explode('::', $decoded);

        $is_encrypted = count($parts) === 2 && !empty($parts[0]) && !empty($parts[1]);

        return $is_encrypted;
    }
}
