<?php

namespace Gigneo;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Class Modules
 *
 * Plugin setup class for Gigneo.
 *
 * @since 0.0.1
 */
class Modules {


	/**
	 * The single instance of the class.
	 *
	 * @var Modules|null
	 * @since 0.0.1
	 */
	private static $instance = null;

	/**
	 * Request-level cache for module_list().
	 *
	 * @var array|null
	 */
	private static $module_list_cache = null;

	/**
	 * Request-level cache for active_modules().
	 *
	 * @var array|null
	 */
	private static $active_modules_cache = null;

	/**
	 * Constructor for the class.
	 *
	 * @since 0.0.1
	 */
	public function __construct() {
		//Include Active Module
		add_action( 'init', array( $this, 'include_modules' ) );
	}

	/**
	 * Flush request-level module caches (e.g. after toggling modules).
	 *
	 * @since 0.0.1
	 * @return void
	 */
	public static function flush_cache() {
		self::$module_list_cache    = null;
		self::$active_modules_cache = null;
	}

	/**
	 * Checks if a given module is active.
	 *
	 * This method verifies whether the specified module exists in the list of active modules.
	 *
	 * @since 0.0.1
	 *
	 * @param string $module The name of the module to check.
	 * @return bool True if the module is active, false otherwise.
	 */
	public static function is_module_active( $module ) {
		if ( empty( $module ) ) {
			return false;
		}

		return in_array( $module, self::active_modules(), true );
	}

	/**
	 * Active modules.
	 *
	 * @since 0.0.1
	 */
	public static function active_modules() {
		if ( null !== self::$active_modules_cache ) {
			return self::$active_modules_cache;
		}

		$module_list   = self::module_list();
		$saved_modules = get_option( '_gigneo_active_modules', array() );

		if ( ! is_array( $saved_modules ) ) {
			$saved_modules = array();
		}

		$active = array_filter(
			$saved_modules,
			function ( $key ) use ( $module_list ) {
				if ( ! isset( $module_list[ $key ] ) ) {
					return false;
				}

				// Pass list so can_use_module does not rebuild it.
				return self::can_use_module( $key, $module_list );
			}
		);

		// Fallback defaults
		if ( empty( $active ) ) {
			foreach ( $module_list as $key => $module ) {
				if ( ! empty( $module['default_active'] ) ) {
					$active[] = $key;
				}
			}
		}

		self::$active_modules_cache = apply_filters( 'gigneo_active_modules', array_values( $active ) );

		return self::$active_modules_cache;
	}

	/**
	 * Module list.
	 *
	 * @since 0.0.1
	 */
	public static function module_list() {
		if ( null !== self::$module_list_cache ) {
			return self::$module_list_cache;
		}

		$modules = array(
			'switch_role'           => array(
				'name'           => esc_html__( 'Switch Role', 'gigneo' ),
				'description'    => esc_html__( 'Allows users to switch roles within the platform seamlessly. Useful for multi-role accounts.', 'gigneo' ),
				'default_active' => true,
				'preview_url'    => '',
				'doc_url'        => 'https://gigneo.com/docs/freelance-service-marketplace/modules/switch-role/',
				'image'          => GIGNEO_DIR_URL . 'assets/admin/img/modules/switch-role.png',
			),
			'social_profiles'       => array(
				'name'           => esc_html__( 'Social Profiles', 'gigneo' ),
				'description'    => esc_html__( 'Allows users to manage and display social profile details. Enhances user interaction.', 'gigneo' ),
				'default_active' => true,
				'preview_url'    => '',
				'doc_url'        => 'https://gigneo.com/docs/freelance-service-marketplace/modules/social-profiles/',
				'image'          => GIGNEO_DIR_URL . 'assets/admin/img/modules/social-profiles.png',
			),
			'email_verification'    => array(
				'name'           => esc_html__( 'Email Verification', 'gigneo' ),
				'description'    => esc_html__( 'Ensures account authenticity by requiring email verification. Enhances security and trust.', 'gigneo' ),
				'default_active' => true,
				'preview_url'    => '',
				'doc_url'        => 'https://gigneo.com/docs/freelance-service-marketplace/modules/email-verification/',
				'image'          => GIGNEO_DIR_URL . 'assets/admin/img/modules/email-verification.png',
			),
			'elementor'             => array(
				'name'           => esc_html__( 'Elementor', 'gigneo' ),
				'description'    => esc_html__( 'Enables Elementor support for easy page customization. Useful for designing user-friendly layouts.', 'gigneo' ),
				'helper_text'    => esc_html__( 'Requires Elementor to be installed and activated.', 'gigneo' ),
				'default_active' => true,
				'preview_url'    => '',
				'doc_url'        => 'https://gigneo.com/docs/freelance-service-marketplace/modules/elementor/',
				'image'          => GIGNEO_DIR_URL . 'assets/admin/img/modules/elementor.png',
			),
			'deactivate_account'    => array(
				'name'           => esc_html__( 'Account Deactivation', 'gigneo' ),
				'description'    => esc_html__( 'Allows users to deactivate accounts temporarily while preserving data for reactivation.', 'gigneo' ),
				'default_active' => true,
				'preview_url'    => '',
				'doc_url'        => 'https://gigneo.com/docs/freelance-service-marketplace/modules/account-deactivation/',
				'image'          => GIGNEO_DIR_URL . 'assets/admin/img/modules/account-deactivation.png',
			),
			'close_account'         => array(
				'name'           => esc_html__( 'Account Closure', 'gigneo' ),
				'description'    => esc_html__( 'Allows users to permanently close their accounts and stop further platform activity.', 'gigneo' ),
				'default_active' => true,
				'preview_url'    => '',
				'doc_url'        => 'https://gigneo.com/docs/freelance-service-marketplace/modules/account-closure/',
				'image'          => GIGNEO_DIR_URL . 'assets/admin/img/modules/account-closure.png',
			),
			'identity_verification' => array(
				'name'        => esc_html__( 'Identity Verification', 'gigneo' ),
				'description' => esc_html__( 'Verifies user identities through submitted details. Increases platform security.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/identity-verification/',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/identity-verification.png',
			),
			'timezone'              => array(
				'name'        => esc_html__( 'Timezone', 'gigneo' ),
				'description' => esc_html__( 'Assigns a specific timezone to each user, ensuring all dates and activities display in their local time.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/timezone/',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/timezone.png',
			),
			'block'                 => array(
				'name'        => esc_html__( 'Block', 'gigneo' ),
				'description' => esc_html__( 'Enables the admin to block user profiles, service and jobs for better management and security.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/block/',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/block.png',
			),
			'layout_builder'        => array(
				'name'        => esc_html__( 'Layout Builder', 'gigneo' ),
				'description' => esc_html__( 'Drag-and-drop tool for creating custom layouts by using elementor. Useful for personalized site designs.', 'gigneo' ),
				'helper_text' => esc_html__( 'Requires Elementor plugin to be installed and activated.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/layout-builder',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/layout-builder.png',
			),
			'dynamic_tags'          => array(
				'name'        => esc_html__( 'Dynamic Tags', 'gigneo' ),
				'description' => esc_html__( 'Seamlessly display real-time content across your Elementor-powered pages.', 'gigneo' ),
				'helper_text' => esc_html__( 'Requires Elementor plugin to be installed and activated.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/dynamic-tags',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/dynamic-tags.png',
			),
			'report_abuse'          => array(
				'name'        => esc_html__( 'Report Abuse', 'gigneo' ),
				'description' => esc_html__( 'Customers can report fraudulent item to maintain a reliable and honest marketplace.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/report-abuse',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/report-abuse.png',
			),
			'map'                   => array(
				'name'        => esc_html__( 'Maps', 'gigneo' ),
				'description' => esc_html__( 'Integrates location-based features using maps. Helps users find and manage locations.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/map',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/map.png',
			),
			'multi_location'        => array(
				'name'        => esc_html__( 'Multi Locations', 'gigneo' ),
				'description' => esc_html__( 'Allows adding multiple locations for services seamlessly, making it easier to manage coverage areas.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/multi-location',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/multi-locations.png',
			),
			'dispute'               => array(
				'name'        => esc_html__( 'Disputes', 'gigneo' ),
				'description' => esc_html__( 'Adds a module for resolving disputes between users. Helps ensure fair transactions.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/dispute',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/dispute.png',
			),
			'social_auth'           => array(
				'name'        => esc_html__( 'Social Auth', 'gigneo' ),
				'description' => esc_html__( 'Allows users to log in using social accounts. Simplifies registration and access.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/social-auth',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/social-auth.png',
			),
			'monthly_credit'        => array(
				'name'        => esc_html__( 'Monthly Credits', 'gigneo' ),
				'description' => esc_html__( 'Enables a feature that auto-assigns monthly credits to each account.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/monthly-credit',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/monthly-credits.png',
			),
			'credit_plans'          => array(
				'name'        => esc_html__( 'Credit Plans', 'gigneo' ),
				'description' => esc_html__( 'Allows users to purchase tier-based credit packages for their account.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/credit-plan',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/credit-plans.png',
			),
			'live_chat'             => array(
				'name'        => esc_html__( 'Live Chat', 'gigneo' ),
				'description' => esc_html__( 'Enables chat features for user communication. Enhances engagement and support.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/live-chat',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/live-chat.png',
			),
			'profile_health'        => array(
				'name'        => esc_html__( 'Profile Health', 'gigneo' ),
				'description' => esc_html__( 'Measures profile completeness based on filled fields, boosting visibility and credibility.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/profile-health',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/profile-health.png',
			),
			'vacation_mode'         => array(
				'name'        => esc_html__( 'Vacation Mode', 'gigneo' ),
				'description' => esc_html__( 'Lets users temporarily pause activities with vacation mode.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/vacation-mode',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/vacation-mode.png',
			),
			'support'               => array(
				'name'        => esc_html__( 'Support', 'gigneo' ),
				'description' => esc_html__( 'Activates the support module for assistance. Helps users resolve issues efficiently.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/support',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/support.png',
			),
			'commission_tier'       => array(
				'name'        => esc_html__( 'Commission Tiers', 'gigneo' ),
				'description' => esc_html__( 'Apply dynamic platform commission rates based on order range for flexible fee management.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/commission-tier',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/tier-commission.png',
			),
			'withdrawal_fee'        => array(
				'name'        => esc_html__( 'Withdrawal Fee', 'gigneo' ),
				'description' => esc_html__( 'Apply dynamic withdraw fee rates based on withdraw payouts.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/withdrawal-fee',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/withdraw-fee.png',
			),
			'addons'                => array(
				'name'        => esc_html__( 'Custom Addons', 'gigneo' ),
				'description' => esc_html__( 'Enhance your service with a custom add-on with flexible options.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/custom-addons',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/addons.png',
			),
			'real_time'             => array(
				'name'        => esc_html__( 'Real-Time', 'gigneo' ),
				'description' => esc_html__( 'Enables real-time notifications powered by Pusher.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/real-time',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/real-time.png',
			),
			'bulk_assign'           => array(
				'name'        => esc_html__( 'Bulk Assign', 'gigneo' ),
				'description' => esc_html__( 'Allows the admin to add or remove wallet funds and credits for users efficiently.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/bulk-assign',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/bulk-assign.png',
			),
			'intake_form'           => array(
				'name'        => esc_html__( 'Intake Form', 'gigneo' ),
				'description' => esc_html__( 'Create custom forms during hiring, freelancers fill them for jobs and employers for services.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/intake-form',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/intake-form.png',
			),
			'extend_delivery'       => array(
				'name'        => esc_html__( 'Extend Delivery', 'gigneo' ),
				'description' => esc_html__( 'Extend the delivery deadline further to allow more time for successful order completion.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/extend-delivery',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/extend-delivery.png',
			),
			'custom_payouts'        => array(
				'name'        => esc_html__( 'Custom Payouts', 'gigneo' ),
				'description' => esc_html__( 'Allow custom withdrawal payouts with personalized options.', 'gigneo' ),
				'is_pro'      => true,
				'preview_url' => '',
				'doc_url'     => 'https://gigneo.com/docs/freelance-service-marketplace/premium-modules/custom-payouts',
				'image'       => GIGNEO_DIR_URL . 'assets/admin/img/modules/custom-payouts.png',
			),
		);

		self::$module_list_cache = apply_filters( 'gigneo_module_list', $modules );

		return self::$module_list_cache;
	}

	/**
	 * Include modules.
	 *
	 * @since 0.0.1
	 */
	public function include_modules() {

		$module_list    = self::module_list();
		$active_modules = self::active_modules();

		foreach ( $active_modules as $module ) {

			if ( isset( $module_list[ $module ] ) ) {
				$class_base = implode( '_', array_map( 'ucfirst', explode( '_', $module ) ) );
				$class      = "\\Gigneo\\Modules\\$class_base";
				if ( class_exists( $class ) ) {
					$class::instance();
				}
			}
		}
	}

	/**
	 * Determine whether a module can be used.
	 *
	 * @since 0.0.1
	 *
	 * @param string     $module_key The unique module key.
	 * @param array|null $modules    Optional pre-fetched module list.
	 * @return bool True if the module is available, otherwise false.
	 */
	public static function can_use_module( $module_key, $modules = null ) {

		if ( null === $modules ) {
			$modules = self::module_list();
		}

		if ( empty( $module_key ) || ! isset( $modules[ $module_key ] ) ) {
			return false;
		}

		return (bool) apply_filters( 'gigneo_can_use_module', true, $module_key );
	}

	/**
	 * Ensures only one instance of the class is loaded or can be loaded.
	 *
	 * @return Modules
	 * @since 0.0.1
	 */
	public static function instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}

		return self::$instance;
	}
}
