<?php

/**
 * @see https://developer.wordpress.org/plugins/settings/options-api/
 */

namespace Alma\Gateway\Infrastructure\Repository;

if ( ! defined( 'ABSPATH' ) ) {
	die( 'Not allowed' ); // Exit if accessed directly.
}

use Alma\Vendor\Alma\Plugin\Infrastructure\Repository\ConfigRepositoryInterface;

/**
 * Class ConfigAdapter to manage WordPress/WooCommerce options.
 */
class ConfigRepository implements ConfigRepositoryInterface {

	/** Generated by WooCommerce in WC_Settings_API::get_option_key(). */
	const OPTIONS_KEY = 'woocommerce_alma_config_gateway_settings';

	/**
	 * Get the value of all settings.
	 *
	 * @param array $arrayFilter Optional. An array to filter the settings. Not used in this implementation.
	 *
	 * @return array The array of settings, or an empty array.
	 */
	public function getSettings( array $arrayFilter = [] ): array {
		$settings = get_option( self::OPTIONS_KEY ) ?? array();
		$settings = is_array( $settings ) ? $settings : array();

		if ( empty( $arrayFilter ) ) {
			return $settings;
		} else {
			$filteredSettings = [];
			foreach ( $arrayFilter as $key ) {
				if ( isset( $settings[ $key ] ) ) {
					$filteredSettings[ $key ] = $settings[ $key ];
				}
			}

			return $filteredSettings;
		}
	}

	/**
	 * Check if the setting exists in the settings array.
	 *
	 * @param string $setting The setting name to check for existence.
	 *
	 * @return bool True if the setting exists, false otherwise.
	 */
	public function hasSetting( string $setting ): bool {
		$settings = $this->getSettings();

		return isset( $settings[ $setting ] );
	}

	/**
	 * Add a specific setting value.
	 *
	 * @param string $setting The setting name to update.
	 * @param mixed  $value The value to set for the setting.
	 *
	 * @return bool True if the setting was updated, false otherwise.
	 */
	public function createSetting( string $setting, $value ): bool {
		$options             = $this->getSettings();
		$options[ $setting ] = $value;

		return update_option( self::OPTIONS_KEY, $options );
	}

	/**
	 * Update a specific setting value.
	 *
	 * @param string $setting The setting name to update.
	 * @param mixed  $value The value to set for the setting.
	 *
	 * @return bool True if the setting was updated, false otherwise.
	 */
	public function updateSetting( string $setting, $value ): bool {
		$options             = $this->getSettings();
		$options[ $setting ] = $value;

		return update_option( self::OPTIONS_KEY, $options );
	}

	/**
	 * Delete a specific setting from the settings array.
	 *
	 * @param string $setting The setting name to delete.
	 *
	 * @return bool True if the setting was deleted, false otherwise.
	 */
	public function deleteSetting( string $setting ): bool {
		$settings = $this->getSettings();
		unset( $settings[ $setting ] );

		return update_option( self::OPTIONS_KEY, $settings );
	}
}
