<?php
/**
 * Plugin specific helpers.
 *
 * @package StrategySuite
 */

namespace StrategySuite;

/**
 * Get an initialized class by its full class name, including namespace.
 *
 * @param string $class_name The class name including the namespace.
 *
 * @return false|Module
 */
function get_module( $class_name ) {
	return \StrategySuite\ModuleInitialization::instance()->get_class( $class_name );
}

/**
 * Makes the is_plugin_active function available before WP loads.
 *
 * @param string $plugin The slug/path of plugin to check.
 *
 * @return boolean Whether or not the plugin is active.
 */
function is_plugin_active( $plugin ) {
	return in_array( $plugin, (array) get_option( 'active_plugins', array() ) );
}

/** Get the Nth field ID of a given field type.
 *
 * @param array  $form The form object.
 * @param string $field_type The field type to search for.
 * @param int    $n The Nth field to find.
 */
function get_nth_field_id( $form, $field_type, $n ) {
	$count = 0;

	foreach ( $form['fields'] as $field ) {
		if ( $field->type == $field_type ) {
			$count++;

			if ( $count == $n ) {
				return $field->id;
			}
		}
	}

	return null;
}

/**
 * Get the site's domain.
 *
 * @return string
 */
function get_site_domain() {
	$site_domain = parse_url( get_home_url(), PHP_URL_HOST );

	if ( 'localhost' === $site_domain ) {
		$site_domain = 'strategydemo.com';
	}

	return $site_domain;
}

/**
 * Check if the given email address belongs to the same domain.
 *
 * @param string $email       The email address to check.
 * @param string $site_domain The domain to compare against.
 *
 * @return bool
 */
function is_same_domain( $email, $site_domain ) {
	if ( empty( $email ) || ! is_email( $email ) ) {
		return false;
	}

	$email_domain = substr( strrchr( $email, '@' ), 1 );

	return strtolower( $email_domain ) === strtolower( $site_domain );
}

/**
 * Determine the default sender email based on site settings.
 *
 * @return string
 */
function determine_sender_email() {
	$site_domain  = get_site_domain();
	$sender_email = '';

	if ( is_plugin_active( 'gravitysmtp/gravitysmtp.php' ) ) {
		$settings = get_option( 'gravitysmtp_amazon' );
		if ( ! empty( $settings ) ) {
			$settings = json_decode( $settings );
			if ( isset( $settings->from_email ) ) {
				return $settings->from_email;
			}
		}
	}

	// Fallback to a no-reply address for the current domain if not set or from another domain.
	if ( empty( $sender_email ) || ! is_same_domain( $sender_email, $site_domain ) ) {
		$sender_email = 'no-reply@' . $site_domain;
	}

	return $sender_email;
}
