<?php

namespace WDevs\CustomerOrderExport\Clients;

use WDevs\CustomerOrderExport\Helper;

/**
 * Base class for all client implementations
 *
 * Provides common functionality like encryption/decryption for OAuth tokens
 * and other sensitive data.
 *
 * @since 1.0.0
 */
abstract class ClientProcessor {
	
	use Helper;

	/**
	 * Get DataEncryption instance
	 *
	 * @return DataEncryption
	 */
	protected static function get_encryption() {
		static $encryption = null;
		if ( $encryption === null ) {
			$encryption = new DataEncryption();
		}
		return $encryption;
	}

	/**
	 * Encrypt sensitive data using DataEncryption
	 *
	 * @param string $data
	 * @return string
	 */
	protected static function encrypt_data( $data ) {
		if ( empty( $data ) ) {
			return '';
		}

		return self::get_encryption()->encrypt( $data );
	}

	/**
	 * Decrypt sensitive data using DataEncryption
	 *
	 * @param string $encrypted_data
	 * @return string
	 */
	protected static function decrypt_data( $encrypted_data ) {
		if ( empty( $encrypted_data ) ) {
			return '';
		}

		return self::get_encryption()->decrypt( $encrypted_data );
	}

	/**
	 * Get and decrypt user meta value
	 *
	 * @param int $user_id
	 * @param string $meta_key
	 * @return string
	 */
	protected static function get_encrypted_user_meta( $user_id, $meta_key ) {
		$encrypted_value = get_user_meta( $user_id, $meta_key, true );
		return self::decrypt_data( $encrypted_value );
	}

	/**
	 * Encrypt and store user meta value
	 *
	 * @param int $user_id
	 * @param string $meta_key
	 * @param string $value
	 * @return bool
	 */
	protected static function update_encrypted_user_meta( $user_id, $meta_key, $value ) {
		$encrypted_value = self::encrypt_data( $value );
		if ( false === $encrypted_value ) {
			return false;
		}

		return update_user_meta( $user_id, $meta_key, $encrypted_value ) !== false;
	}

}
