<?php
/**
 * Settings store.
 *
 * @package Lucrativeit_Subscription_Recurring_Billing
 */

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

/**
 * Thin wrapper around the lucrsure_settings option array.
 */
class LUCRSURE_Settings {

	/**
	 * Cached settings.
	 *
	 * @var array
	 */
	protected $data;

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->data = get_option( 'lucrsure_settings', array() );
		if ( ! is_array( $this->data ) ) {
			$this->data = array();
		}
	}

	/**
	 * Get a top-level setting.
	 *
	 * @param string $key     Setting key.
	 * @param mixed  $default Default value.
	 * @return mixed
	 */
	public function get( $key, $default = null ) {
		return isset( $this->data[ $key ] ) ? $this->data[ $key ] : $default;
	}

	/**
	 * Get a nested gateway config.
	 *
	 * @param string $gateway Gateway id.
	 * @return array
	 */
	public function gateway( $gateway ) {
		$gateways = $this->get( 'gateways', array() );
		return isset( $gateways[ $gateway ] ) ? $gateways[ $gateway ] : array();
	}

	/**
	 * Is the plugin running in WooCommerce mode?
	 *
	 * @return bool
	 */
	public function is_woocommerce_mode() {
		return 'woocommerce' === $this->get( 'subscription_engine', 'custom' );
	}

	/**
	 * Persist the entire settings array.
	 *
	 * @param array $data Settings.
	 */
	public function save( array $data ) {
		$this->data = $data;
		update_option( 'lucrsure_settings', $data );
	}

	/**
	 * Merge a partial array into the stored settings.
	 *
	 * @param array $partial Partial settings.
	 */
	public function merge( array $partial ) {
		$this->data = array_merge( $this->data, $partial );
		update_option( 'lucrsure_settings', $this->data );
	}

	/**
	 * Return the full settings array.
	 *
	 * @return array
	 */
	public function all() {
		return $this->data;
	}
}
