<?php
/**
 * Array manipulation helper functions.
 *
 * @package Awesomemotive\Rewardswp\Helpers
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Helpers;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use stdClass;

/**
 * Filter array by allowed keys.
 *
 * @since 1.0.0
 *
 * @param array $input     The input array to filter.
 * @param array $keys      The list of keys to retain.
 *
 * @return array Filtered array containing only the specified keys.
 */
function filter_array_by_keys( array $input, array $keys ): array {
	return array_intersect_key( $input, array_flip( $keys ) );
}


/**
 * Recursively merges two arrays, replacing values from the first array with those from the second.
 * Maintains values from the first array that do not exist in the second.
 *
 * @param array $array1 The base array.
 * @param array $array2 The array with values to overwrite.
 *
 * @return array The merged array.
 * @since 1.0.0
 */
function recursive_array_merge( array $array1, array $array2 ): array {
	foreach ( $array2 as $key => $value ) {
		if ( is_array( $value ) && isset( $array1[ $key ] ) && is_array( $array1[ $key ] ) ) {
			// Merge recursively if both values are arrays.
			$array1[ $key ] = recursive_array_merge( $array1[ $key ], $value );
		} else {
			// Overwrite or add the value from array2.
			$array1[ $key ] = $value;
		}
	}

	return $array1;
}

/**
 * Return an array with the values separated by comma.
 *
 * Mainly intended to be used to save IDs to the database using the comma-separated format.
 *
 * @since 1.0.0
 *
 * @param array $array
 * @return string
 */
function comma_separated_array( array $array ): string {
	if ( empty( $array ) ) {
		return '';
	}

	return implode( ',', $array );
}

/**
 * Check whether an array is a list (sequential integer keys starting from 0).
 *
 * Polyfill for PHP 8.1's array_is_list().
 *
 * @since 1.4.2
 *
 * @param array $array The array to check.
 *
 * @return bool True if the array is a list, false otherwise.
 */
function is_list( array $array ): bool {
	if ( function_exists( 'array_is_list' ) ) {
		return array_is_list( $array );
	}

	if ( [] === $array ) {
		return true;
	}

	return array_keys( $array ) === range( 0, count( $array ) - 1 );
}

/**
 * Converts an array of associative arrays into an array of stdClass objects.
 *
 * @since 1.0.0
 *
 * @param array $array Input array of associative arrays.
 *
 * @return array Array of stdClass objects.
 */
function convert_array_to_std_objects( array $array ): array {
	if ( empty( $array ) || ! is_array( reset( $array ) ) ) {
		return [];
	}

	return array_map(
		function ( $item ) {
			if ( ! is_array( $item ) ) {
				return new stdClass();
			}

			$object = new stdClass();
			foreach ( $item as $key => $value ) {
				if ( is_scalar( $value ) || is_array( $value ) || is_object( $value ) ) {
					$object->$key = $value;
				}
			}

			return $object;
		},
		$array
	);
}
