<?php
/**
 * Core plugin functionality.
 *
 * @package CommonFrameworkPlugin
 */

namespace CommonFrameworkPlugin\Core;

use CommonFrameworkPlugin\ModuleInitialization;
use WP_Error;

/**
 * Default setup routine
 *
 * @return void
 */
function setup() {
	$n = function ( $function ) {
		return __NAMESPACE__ . "\\$function";
	};

	add_action( 'init', $n( 'i18n' ) );
	add_action( 'init', $n( 'init' ), apply_filters( 'common_framework_plugin_init_priority', 4 ) );

	do_action( 'common_framework_plugin_loaded' );
}

/**
 * Registers the default textdomain.
 *
 * @return void
 */
function i18n() {
	$locale = apply_filters( 'plugin_locale', get_locale(), 'common-framework-plugin' );
	load_textdomain( 'common-framework-plugin', WP_LANG_DIR . '/common-framework-plugin/common-framework-plugin-' . $locale . '.mo' );
	load_plugin_textdomain( 'common-framework-plugin', false, plugin_basename( COMMON_FRAMEWORK_PLUGIN_PATH ) . '/languages/' );
}

/**
 * Initializes the plugin and fires an action other plugins can hook into.
 *
 * @return void
 */
function init() {
	do_action( 'common_framework_plugin_before_init' );

	// If the composer.json isn't found, trigger a warning.
	if ( ! file_exists( COMMON_FRAMEWORK_PLUGIN_PATH . 'composer.json' ) ) {
		add_action(
			'admin_notices',
			function () {
				$class = 'notice notice-error';
				$message = sprintf( __( 'The composer.json file was not found within %s. No classes will be loaded.', 'common-framework-plugin' ), COMMON_FRAMEWORK_PLUGIN_PATH );
				printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( $message ) );
			}
		);
		return;
	}

	if ( ! class_exists( 'FacetWP' ) ) {
		add_action(
			'admin_notices',
			function () {
				$class = 'notice notice-error';
				$message = sprintf( __( 'FacetWP is not active. Please install and activate the FacetWP plugin.', 'common-framework-plugin' ), COMMON_FRAMEWORK_PLUGIN_PATH );
				printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( $message ) );
			}
		);
		return;
	}

	ModuleInitialization::instance()->init_classes();
	do_action( 'common_framework_plugin_init' );
}

/**
 * Activate the plugin
 *
 * @return void
 */
function activate() {
	// First load the init scripts in case any rewrite functionality is being loaded
	init();
	flush_rewrite_rules();
	add_option( 'common_framework_plugin_repo', 'Strategyllcweb/Strategy-Plugin-Scaffold' );
	add_option( 'common_framework_plugin_branch', 'master' );
}

/**
 * Deactivate the plugin
 *
 * Uninstall routines should be in uninstall.php
 *
 * @return void
 */
function deactivate() {
	delete_option( 'common_framework_plugin_repo' );
	delete_option( 'common_framework_plugin_branch' );
}
