<?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 );
		return update_user_meta( $user_id, $meta_key, $encrypted_value ) !== false;
	}

	/**
	 * Get or create a persistent hash for user ID
	 *
	 * Creates a unique hash for the user and stores it in user meta.
	 * Once created, the same hash will always be returned for this user.
	 *
	 * @param int $user_id
	 * @return string
	 */
	public static function get_or_create_persistent_user_hash( $user_id ) {
		$meta_key = 'wdevs_coe_user_hash';
		$existing_hash = get_user_meta( $user_id, $meta_key, true );

		if ( !empty( $existing_hash ) ) {
			return $existing_hash;
		}

		$salt = wp_salt( 'auth' );
		$hash = hash( 'sha256', $user_id . $salt );
		
		update_user_meta( $user_id, $meta_key, $hash );

		return $hash;
	}

}