<?php
/**
 * Global functions
 *
 * @package Nisje
 */

defined( 'ABSPATH' ) || die( 'Shame on you' );

/**
 * Get plugin version number
 *
 * @param string $type Version type.
 */
function nisje_get_version( $type = 'plugin_version' ) {
	if ( in_array( $type, [ 'plugin_version', 'db_version' ], true ) ) {
		return nisje()->versions[ $type ];
	} else {
		return false;
	}
}

/**
 * Get Setting
 *
 * @param string $name     Setting name.
 * @param string $group    Setting group.
 * @param mixed  $fallback Setting fallback.
 * @return mixed Setting
 */
function nisje_get_setting( $name, $group = false, $fallback = null ) {
	return nisje()->settings->get_setting( $name, $group, $fallback );
}

/**
 * Return path inside plugin folder
 *
 * @param string $path Relative path from plugin root.
 * @return string Full path
 */
function nisje_get_path( $path ) {
	return nisje()->path . $path;
}

/**
 * Return dir inside plugin folder
 *
 * @param string $path Relative dir from plugin root.
 * @return string Full dir
 */
function nisje_get_dir( $path ) {
	return nisje()->dir . $path;
}

/**
 * Check if exists and include
 *
 * @param string $file File path.
 */
function nisje_include( $file ) {
	$path = nisje_get_path( $file );

	if ( file_exists( $path ) ) {
		include_once $path;
	}
}

/**
 * Register Component
 *
 * @param object $component Component object.
 * @return void
 */
function nisje_register_component( $component ) {
	if ( did_action( 'nisje_components_registered' ) ) {
		_doing_it_wrong( __METHOD__, esc_html__( 'Nisje components have already been registered. Please run nisje_register_component() on action nisje_register_components.', 'nisje' ), '1.0.0' );
	}

	add_filter( 'nisje_components', function( $components ) use ( $component ) {
		$components[] = $component;

		return $components;
	} );
}

/**
 * Return component.
 *
 * @param string $key Component key.
 * @return array Active components
 */
function nisje_get_component( $key ) {
	if ( ! did_action( 'nisje_components_registered' ) ) {
		_doing_it_wrong( __METHOD__, esc_html__( 'Nisje components not yet registered.', 'nisje' ), '1.0.0' );
	}

	$key = sanitize_key( $key );
	if ( isset( nisje()->components[ $key ] ) ) {
		return nisje()->components[ $key ];
	}

	return false;
}

/**
 * Return a list of active components.
 *
 * @return array Active components
 */
function nisje_get_active_components() {
	if ( ! did_action( 'nisje_components_registered' ) ) {
		_doing_it_wrong( __METHOD__, esc_html__( 'Nisje components not yet registered.', 'nisje' ), '1.0.0' );
	}

	$components = [];

	foreach ( nisje()->components as $key => $component ) {
		$components[ $key ] = [
			'label'    => $component->label,
			'settings' => isset( $component->public_settings ) ? $component->public_settings : [],
		];
	}

	return $components;
}
