<?php
/** Options
 *
 * @package Bw-Winners-Network
 */

namespace BwWinnersNetwork;

if ( ! class_exists( __NAMESPACE__ . '\Options' ) ) {
	/**
	 * Manages options used to configure the plugin.
	 */
	class Options {
		/**
		 * WordPress option name for BwWinnersNetwork options
		 *
		 * @var array
		 */
		public static $option = 'Bw_Winners_Network_options';

		/**
		 * BwWinnersNetwork allowed options
		 *
		 * @var array
		 */
		protected static $keys = array(
			'database_version',
			'example',
		);

		/**
		 * BwWinnersNetwork option default values
		 *
		 * @var array
		 */
		public static $defaults = array(
			'database_version' => '0.0.0',
			'example'          => 'test',
		);
		/**
		 * Gets the BwWinnersNetwork options.
		 *
		 * @return array BwWinnersNetwork options.
		 */
		public static function get_options() {
			$options = get_option( self::$option, null );

			if ( ! is_array( $options ) ) {
				return self::$defaults;
			}

			foreach ( self::$defaults as $key => $value ) {
				if ( ! isset( $options[ $key ] ) ) {
					$options[ $key ] = $value;
				}
			}
			return $options;
		}

		/**
		 * Updates the BwWinnersNetwork options
		 *
		 * @param array $update Options to update.
		 *
		 * @return array BwWinnersNetwork options.
		 */
		public static function update_options( $update ) {
			$options = self::get_options();

			foreach ( self::$keys as $key ) {
				if ( isset( $update[ $key ] ) ) {
					$options[ $key ] = $update[ $key ];
				}
			}

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

		/**
		 * Gets a single BwWinnersNetwork option
		 *
		 * @param string $key  The option name.
		 *
		 * @return mixed
		 */
		public static function get_option( $key, $default = null ) {
			if ( ! in_array( $key, self::$keys ) ) {
				return $default;  // Invalid key protection
			}
			$options = self::get_options();
			return isset( $options[ $key ] ) ? $options[ $key ] : $default;
		}

		/**
		 * Updates a single BwWinnersNetwork option
		 *
		 * @param string $key  The option name.
		 * @param mixed  $value The option value.
		 */
		public static function update_option( $key, $value ) {
			$options         = self::get_options();
			$options[ $key ] = $value;
			self::update_options( $options );
		}

		/**
		 * Deletes a single BwWinnersNetwork option
		 *
		 * @param string $key  The option name.
		 */
		public static function delete_option( $key ) {
			$options = self::get_options();
			unset( $options[ $key ] );
			self::update_options( $options );
		}
	}
}
