<?php

namespace WPDesk\FakturyKSEF\Services;

use phpseclib3\Crypt\PublicKeyLoader;
use phpseclib3\Crypt\RSA;

class EncryptionService {
	public function get_public_key_from_certificates( array $certificates, string $usage_type ): string {
		foreach ( $certificates as $cert ) {
			if ( in_array( $usage_type, $cert['usage'], true ) ) {
				$der_cert = base64_decode( $cert['certificate'], true ); //phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
				$pem_cert = "-----BEGIN CERTIFICATE-----\n" . chunk_split( base64_encode( $der_cert ), 64 ) . "-----END CERTIFICATE-----\n"; //phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode

				$public_key_resource = openssl_pkey_get_public( $pem_cert );
				if ( $public_key_resource === false ) {
					throw new \Exception( esc_html__( 'Failed to parse public key.', 'ksef-for-flexible-invoices' ) );
				}
				$public_key_details = openssl_pkey_get_details( $public_key_resource );
				return $public_key_details['key'];
			}
		}
		// translators: %1 usage type
		throw new \Exception( sprintf( esc_html__( 'Unable to fetch public key for usage: %s.', 'ksef-for-flexible-invoices' ), $usage_type ) );
	}

	public function encrypt_invoice( string $invoice_xml, string $symmetric_key, string $iv ): string {
		return openssl_encrypt( $invoice_xml, 'aes-256-cbc', $symmetric_key, OPENSSL_RAW_DATA, $iv );
	}

	public function encrypt_key( string $key, string $ksef_public_key ): string {
		$public_loaded_key = PublicKeyLoader::load( $ksef_public_key );
		return $public_loaded_key //@phpstan-ignore method.notFound
			->withPadding( RSA::ENCRYPTION_OAEP )
			->withHash( 'sha256' )
			->withMGFHash( 'sha256' )
			->encrypt( $key );
	}

	public function generate_verification_key( string $invoice_xml_content ): string {
		$hash_bytes = hash( 'sha256', $invoice_xml_content, true );
		return base64_encode( $hash_bytes ); //phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
	}
}
