<?php
/**
 * Plugin specific helpers.
 *
 * @package CommonFrameworkPlugin
 */

namespace CommonFrameworkPlugin;

/**
 * Get an initialized class by its full class name, including namespace.
 *
 * @param string $class_name The class name including the namespace.
 *
 * @return false|Module
 */
function get_module( $class_name ) {
	return \CommonFrameworkPlugin\ModuleInitialization::instance()->get_class( $class_name );
}

/**
 * Writes logs if debugging is enabled.
 *
 * @param mixed $log Information to log.
 */
function write_log( $log ) {
	$log_dir  = WP_CONTENT_DIR . '/debug';
	$log_file = $log_dir . '/debug.log';

	if ( ! file_exists( $log_dir ) ) {
		wp_mkdir_p( $log_dir );
	}

	if ( is_array( $log ) || is_object( $log ) ) {
		$log = print_r( $log, true );
	}

	file_put_contents(
		$log_file,
		$log . PHP_EOL,
		FILE_APPEND | LOCK_EX
	);
}

/**
 * Merge two arrays, preferring the values from the second array ($payload)
 * when there are key conflicts.
 *
 * @param array $display_data The first array (to be overwritten).
 * @param array $payload The second array (with preferred values).
 * @return array The merged array.
 */
function custom_array_merge( $display_data, $payload ) {
	// Iterate through the $payload array
	foreach ( $payload as $key => $value ) {
		// If the key exists in both arrays, overwrite the value in $display_data
		if ( isset( $display_data[ $key ] ) && is_array( $value ) && is_array( $display_data[ $key ] ) ) {
			// If both values are arrays, merge them recursively
			$display_data[ $key ] = custom_array_merge( $display_data[ $key ], $value );
		} else {
			// Otherwise, just replace the value
			$display_data[ $key ] = $value;
		}
	}

	return $display_data;
}
