<?php
class AuthHelper
{
    public static function validateToolsKey($request, $config)
    {
        if ($request->get('key') != $config['tools_key']) {
            throw new CustomErrorException(BaseResponse::INVALID_REQUEST, 'Invalid Key');
        }
    }

    public static function encryptMessage($message, $key, $encode = false) {
        $nonceSize = openssl_cipher_iv_length('aes-256-ctr');
        $nonce = openssl_random_pseudo_bytes($nonceSize);

        $ciphertext = openssl_encrypt(
            $message,
            'aes-256-ctr',
            $key,
            OPENSSL_RAW_DATA,
            $nonce
        );

        if ($encode) {
            return base64_encode($nonce.$ciphertext);
        }
        return $nonce.$ciphertext;
    }

    public static function decryptMessage($message, $key, $encoded = false)
    {
        if ($encoded) {
            $message = base64_decode($message, true);
            if ($message === false) {
                throw new Exception('Encryption failure');
            }
        }

        $nonceSize = openssl_cipher_iv_length('aes-256-ctr');
        $nonce = mb_substr($message, 0, $nonceSize, '8bit');
        $ciphertext = mb_substr($message, $nonceSize, null, '8bit');

        return openssl_decrypt(
            $ciphertext,
            'aes-256-ctr',
            $key,
            OPENSSL_RAW_DATA,
            $nonce
        );
    }

    public static function decryptAES256CBC($text) {
        $key = getenv("AES_256_CBC_KEY");
        $iv = getenv("AES_256_CBC_IV");
        return openssl_decrypt(base64_decode($text), 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    }

    public static function encryptAES256CBC($text) {
        $key = getenv("AES_256_CBC_KEY");
        $iv = getenv("AES_256_CBC_IV");
        return base64_encode(openssl_encrypt($text, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv));
    }

    /**
     * @throws ValidationException
     */
    public static function decryptPassword($request, $key = 'password', $hKey = 'h_password') {
        if (empty($request[$key]) && empty($request[$hKey])) {
            throw new ValidationException("Password harus diisi!");
        }
        if (!empty($request[$hKey])) {
            $password = AuthHelper::decryptAES256CBC($request[$hKey]);
        } else {
            $password = $request[$key];
        }

        return $password;
    }

    /**
     * @throws ValidationException
     */
    public static function validatePassword($password) {
        $pattern = '/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/';
        if (!preg_match($pattern, $password)) {
            throw new CustomErrorException(BaseResponse::REGISTRATION_ERROR, "Panjang minimal password 8 karakter. Password harus mengandung huruf besar, huruf kecil, angka dan karakter khusus.");
        }

        return true;
    }
}
