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

namespace Awesomemotive\Rewardswp\Helpers;

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

use Awesomemotive\Rewardswp\Abstracts\AbstractOption;
use Awesomemotive\Rewardswp\Factories\OptionsFactory;
use Awesomemotive\Rewardswp\Interfaces\IntegrationInterface;
use Awesomemotive\Rewardswp\Services\OptionsService;
use Exception;

/**
 * Retrieve a single option value.
 *
 * @since 1.0.0
 *
 * @param string|AbstractOption $name_or_class The setting name or class name.
 * @param string                $group         The group that the option belongs, unnecessary if using class as first parameter.
 *
 * @return mixed
 */
function get_option_value( $name_or_class, string $group = '' ) {
	try {
		$options = am_rewardswp()->get_container()->get( OptionsFactory::class );

		return $options->get_option( $name_or_class, $group )->get_value();
	} catch ( Exception $exception ) {
		return null;
	}
}

/**
 * Retrieve a single option object.
 *
 * @template T of AbstractOption
 * @param class-string<T>|AbstractOption $name_or_class The setting name or class name.
 * @param string                         $group         The group that the option belongs to, unnecessary if using class as first parameter.
 *
 * @return T|null The specific option object or null if not found.
 */
function get_option_object( $name_or_class, string $group = '' ) {
	try {
		$options = am_rewardswp()->get_container()->get( OptionsFactory::class );

		if ( is_null( $options ) ) {
			return null;
		}

		return $options->get_option( $name_or_class, $group );
	} catch ( Exception $exception ) {
		return null;
	}
}

/**
 * Retrieve all options.
 *
 * @since 1.0.0
 *
 * @return array|null
 */
function get_all_options(): ?array {
	try {
		$options_service = am_rewardswp()->get_container()->get( OptionsService::class );

		if ( is_null( $options_service ) ) {
			return null;
		}

		return $options_service->get_options();
	} catch ( Exception $exception ) {
		return null;
	}
}

/**
 * Retrieve the source identifier of the active integration.
 *
 * The integration is a special type of setting that is never saved to the database.
 * It represents the currently active e-commerce platform (WooCommerce, EDD, etc.).
 *
 * @since 1.2.0
 *
 * @return string The source identifier (e.g., 'woocommerce', 'edd') or empty string if not available.
 */
function get_active_integration_source(): string {
	try {
		$integration = am_rewardswp()->get_container()->get( IntegrationInterface::class );

		return $integration ? $integration->get_source() : '';
	} catch ( Exception $exception ) {
		return '';
	}
}
