<?php

namespace StoreEngine;

use StoreEngine\Admin\Settings;
use StoreEngine\Classes\AbstractAddon;
use WP_Error;

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

class Addons {
	public static function init() {
		$self = new self();
		// Load all addons
		$self->addons_loader();
	}

	private function addons_loader() {
		$addons = apply_filters( 'storeengine/addons/loader_args', [
			'paypal'         => 'Paypal',
			'stripe'         => 'Stripe',
			'affiliate'      => 'Affiliate',
			'membership'     => 'Membership',
			'subscription'   => 'Subscription',
			'invoice'        => 'Invoice',
			'email'          => 'Email',
			'webhooks'       => 'Webhooks',
			'migration-tool' => 'MigrationTool',
			'csv'            => 'Csv',
			'catalog-mode'   => 'CatalogMode',
			'razorpay'       => 'Razorpay',
			'paddle'         => 'Paddle',
			'multi-currency'         => 'MultiCurrency',
		] );

		foreach ( $addons as $addon_name => $addon_class_name ) {
			$addon_root_path = STOREENGINE_ADDONS_DIR_PATH . $addon_name . '/';
			$addon_namespace = 'StoreEngine\\Addons\\' . $addon_class_name;

			// Register the addon's root namespace and path.
			Autoload::get_instance()->add_namespace_directory( $addon_namespace, $addon_root_path );

			/**
			 * Initialize the addon's main class.
			 *
			 * @var AbstractAddon $class Addon's main class.
			 */
			$class = $addon_namespace . '\\' . $addon_class_name;
			$class = $class::init();
			$class->run();
		}

		do_action( 'storeengine/addons/loaded' );
	}

	public static function activate( string $addon_slug ) {
		global $storeengine_addons;
		if ( ! isset( $storeengine_addons ) ) {
			Settings::load_settings();
		}

		$data = (array) $storeengine_addons;

		if ( array_key_exists( $addon_slug, $data ) ) {
			if ( $data[$addon_slug] ) {
				// translators: %s: Addon slug.
				return new WP_Error( 'addon_already_activated', sprintf( __( 'Addon %s already activated', 'storeengine' ), $addon_slug ) );
			}
		}

		$storeengine_addons->{$addon_slug} = true;

		update_option( STOREENGINE_ADDONS_SETTINGS_NAME, wp_json_encode( $storeengine_addons ) );

		do_action( "storeengine/addons/activated_{$addon_slug}" );

		return true;
	}

	public static function deactivate( string $addon_slug ) {
		global $storeengine_addons;
		if ( ! isset( $storeengine_addons ) ) {
			Settings::load_settings();
		}

		$data = (array) $storeengine_addons;

		if ( array_key_exists( $addon_slug, $data ) ) {
			if ( !$data[$addon_slug] ) {
				// translators: %s: Addon slug.
				return new WP_Error( 'addon_already_deactivated', sprintf( __( 'Addon %s already deactivated', 'storeengine' ), $addon_slug ) );
			}
		}

		$storeengine_addons->{$addon_slug} = false;

		update_option( STOREENGINE_ADDONS_SETTINGS_NAME, wp_json_encode( $storeengine_addons ) );

		do_action( "storeengine/addons/deactivated_{$addon_slug}" );

		return true;
	}
}
