<?php
declare (strict_types = 1);
namespace ProxyPay\Core;

class Utils
{

	public static function generageUUID(): string
	{
		return trim(file_get_contents('/proc/sys/kernel/random/uuid'));
	}

	public static function checkCredentials($url, $key)
	{
		$api    = new Retailcrm($url, $key);
		$result = $api->getCredentials();
		if (!$result) {
			return -1;
		}
		if (!$result->success) {
			return -2;
		}
		if (
			!in_array('/api/payment/(updateInvoice|check)', $result->credentials) ||
			!in_array('/api/integration-modules/{code}/edit', $result->credentials)
		) {
			return -3;
		}
		return 1;
	}

	public static function encode($data, $key)
	{
		$data  = json_encode($data);
		$ivlen = openssl_cipher_iv_length("AES-128-CBC");
		$iv    = openssl_random_pseudo_bytes($ivlen);
		$data  = openssl_encrypt($data, "AES-128-CBC", $key, OPENSSL_RAW_DATA, $iv);
		$hmac  = hash_hmac('sha256', $data, $key, $as_binary = true);
		$data  = base64_encode($iv . $hmac . $data);
		return $data;
	}

	public static function decode($data, $key)
	{
		$c                  = base64_decode($data);
		$ivlen              = openssl_cipher_iv_length("AES-128-CBC");
		$iv                 = substr($c, 0, $ivlen);
		$hmac               = substr($c, $ivlen, $sha2len = 32);
		$ciphertext_raw     = substr($c, $ivlen + $sha2len);
		$original_plaintext = openssl_decrypt($ciphertext_raw, "AES-128-CBC", $key, $options = OPENSSL_RAW_DATA, $iv);
		$calcmac            = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary = true);
		$data               = [];
		if ($hmac && hash_equals($hmac, $calcmac)) {
			$data = json_decode($original_plaintext, true);
		}
		return $data;
	}

	public static function clearPhone($phone, $prefix = '')
	{
		$phone = preg_replace('/[^0-9]/', '', $phone);
		if (preg_match('/^8(\d{10})$/', $phone, $m)) {
			$phone = $m[1];
		}
		if (preg_match('/^7(\d{10})$/', $phone, $m)) {
			$phone = $m[1];
		}
		if (strlen($phone) == 10) {
			$phone = $prefix . $phone;
		} else {
			$phone = '';
		}
		return $phone;
	}
}
