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

if ( ! class_exists( 'SftcyWordformFeatures' ) ) {
	/**
	 * Central feature-availability helper.
	 *
	 * Keeps premium/basic/free and license-expiry checks in one place so
	 * new features like payments can be gated later without refactoring
	 * every admin view, element renderer, and gateway handler again.
	 */
	class SftcyWordformFeatures {
		private static $wordform_feature_flags_registry = null;

		/**
		 * Current product tier.
		 *
		 * Pro plugin defaults to `pro`. Future basic/free builds can override
		 * this with a constant or filter without changing feature consumers.
		 *
		 * @return string
		 */
		public static function wordform_get_product_tier() {
			$tier = defined( 'WORDFORM_PRODUCT_TIER' ) ? WORDFORM_PRODUCT_TIER : 'pro';
			$tier = apply_filters( 'wordform_product_tier', $tier );
			return sanitize_key( $tier );
		}

		/**
		 * Load the machine-readable feature registry from disk.
		 *
		 * @return array
		 */
		public static function wordform_get_feature_flags_registry() {
			if ( null !== self::$wordform_feature_flags_registry ) {
				return self::$wordform_feature_flags_registry;
			}

			$registry_file = trailingslashit( SFTCY_WORDFORM_PLUGIN_DIR ) . 'features/feature-flags.json';
			$registry      = array(
				'schemaVersion' => 1,
				'features'      => array(),
			);

			if ( file_exists( $registry_file ) ) {
				$raw = file_get_contents( $registry_file );
				$map = json_decode( $raw, true );
				if ( is_array( $map ) && isset( $map['features'] ) && is_array( $map['features'] ) ) {
					$registry = $map;
				}
			}

			self::$wordform_feature_flags_registry = (array) apply_filters( 'wordform_feature_flags_registry', $registry );
			return self::$wordform_feature_flags_registry;
		}

		/**
		 * Get raw feature rule for current tier.
		 *
		 * @param string $feature_key Feature identifier.
		 * @return array
		 */
		public static function wordform_get_feature_rule( $feature_key = '' ) {
			$feature_key = sanitize_key( $feature_key );
			$registry    = self::wordform_get_feature_flags_registry();
			$tier        = self::wordform_get_product_tier();

			if ( empty( $feature_key ) || empty( $registry['features'][ $feature_key ] ) || ! is_array( $registry['features'][ $feature_key ] ) ) {
				return array(
					'feature' => $feature_key,
					'tier'    => $tier,
					'status'  => 'pro' === $tier ? 'full' : 'pro_only',
					'limits'  => array(),
				);
			}

			$feature_map = $registry['features'][ $feature_key ];
			$status      = isset( $feature_map[ $tier ] ) ? sanitize_key( $feature_map[ $tier ] ) : ( 'pro' === $tier ? 'full' : 'pro_only' );
			$limits      = array();

			if ( ! empty( $feature_map['limits'][ $tier ] ) && is_array( $feature_map['limits'][ $tier ] ) ) {
				$limits = $feature_map['limits'][ $tier ];
			}

			return array(
				'feature' => $feature_key,
				'tier'    => $tier,
				'status'  => $status,
				'limits'  => $limits,
			);
		}

		/**
		 * Whether premium features should be restricted by license state.
		 *
		 * Default is false for now to avoid surprising current admin behavior.
		 * Future builds can enable enforcement with a constant/filter.
		 *
		 * @return bool
		 */
		public static function wordform_enforce_license_limits() {
			$enforce = defined( 'WORDFORM_ENFORCE_LICENSE_LIMITS' ) ? (bool) WORDFORM_ENFORCE_LICENSE_LIMITS : false;
			return (bool) apply_filters( 'wordform_enforce_license_limits', $enforce );
		}

		/**
		 * Stored remote license data.
		 *
		 * @return array
		 */
		public static function wordform_get_license_data() {
			$data = get_option( 'wordform_pro_license_data', array() );
			return is_array( $data ) ? $data : array();
		}

		/**
		 * Current normalized license state.
		 *
		 * @return string active|expired|inactive
		 */
		public static function wordform_get_license_state() {
			$license_data = self::wordform_get_license_data();

			if ( empty( $license_data ) ) {
				return 'inactive';
			}

			if ( ! empty( $license_data['isLicenseExpired'] ) ) {
				return 'expired';
			}

			$expiry_datetime = '';
			if ( ! empty( $license_data['subscriptionNextBilledAt'] ) ) {
				$expiry_datetime = sanitize_text_field( $license_data['subscriptionNextBilledAt'] );
			} elseif ( ! empty( $license_data['expiredDateTime'] ) ) {
				$expiry_datetime = sanitize_text_field( $license_data['expiredDateTime'] );
			}

			if ( ! empty( $expiry_datetime ) ) {
				try {
					$current_datetime = new DateTimeImmutable( gmdate( 'Y-m-d H:i:s' ) );
					$license_datetime = new DateTimeImmutable( $expiry_datetime );
					return ( $license_datetime > $current_datetime ) ? 'active' : 'expired';
				} catch ( Exception $e ) {
					return 'inactive';
				}
			}

			return ( ! empty( $license_data['status'] ) && 'success' === $license_data['status'] ) ? 'active' : 'inactive';
		}

		/**
		 * Whether the stored license is currently usable.
		 *
		 * @return bool
		 */
		public static function wordform_is_license_active() {
			return 'active' === self::wordform_get_license_state();
		}

		/**
		 * Default feature flags by tier.
		 *
		 * Keep keys stable so future free/basic builds can selectively disable
		 * premium capabilities without rewriting admin logic.
		 *
		 * @return array
		 */
		public static function wordform_get_default_feature_flags() {
			$tier = self::wordform_get_product_tier();
			$registry = self::wordform_get_feature_flags_registry();
			$feature_flags = array(
				'connections'      => true,
				'payments'         => true,
				'payment_elements' => true,
			);

			if ( ! empty( $registry['features'] ) && is_array( $registry['features'] ) ) {
				foreach ( $registry['features'] as $feature_key => $feature_map ) {
					if ( ! is_array( $feature_map ) ) {
						continue;
					}

					$status = isset( $feature_map[ $tier ] ) ? sanitize_key( $feature_map[ $tier ] ) : ( 'pro' === $tier ? 'full' : 'pro_only' );
					$feature_flags[ sanitize_key( $feature_key ) ] = in_array( $status, array( 'full', 'limited' ), true );
				}
			}

			return (array) apply_filters( 'wordform_feature_flags', $feature_flags, $tier );
		}

		/**
		 * Whether a feature should currently be available.
		 *
		 * @param string $feature_key Feature identifier.
		 * @return bool
		 */
		public static function wordform_is_feature_available( $feature_key = '' ) {
			$feature_key   = sanitize_key( $feature_key );
			$feature_flags = self::wordform_get_default_feature_flags();
			$is_available  = ! empty( $feature_flags[ $feature_key ] );

			if ( $is_available && self::wordform_enforce_license_limits() ) {
				$premium_features = array( 'payments', 'payment_elements', 'stripe_gateway', 'paypal_gateway', 'form_submission_export' );
				if ( in_array( $feature_key, $premium_features, true ) && ! self::wordform_is_license_active() ) {
					$is_available = false;
				}
			}

			return (bool) apply_filters(
				'wordform_is_feature_available',
				$is_available,
				$feature_key,
				self::wordform_get_product_tier(),
				self::wordform_get_license_state()
			);
		}

		/**
		 * Whether a feature is available but limited in the current tier.
		 *
		 * @param string $feature_key Feature identifier.
		 * @return bool
		 */
		public static function wordform_is_feature_limited( $feature_key = '' ) {
			$rule = self::wordform_get_feature_rule( $feature_key );
			return isset( $rule['status'] ) && 'limited' === $rule['status'];
		}

		/**
		 * Get tier-specific limits for a feature.
		 *
		 * @param string $feature_key Feature identifier.
		 * @return array
		 */
		public static function wordform_get_feature_limits( $feature_key = '' ) {
			$rule = self::wordform_get_feature_rule( $feature_key );
			return ! empty( $rule['limits'] ) && is_array( $rule['limits'] ) ? $rule['limits'] : array();
		}

		/**
		 * Feature availability payload for admin UI.
		 *
		 * @param string $feature_key Feature identifier.
		 * @return array
		 */
		public static function wordform_get_feature_availability( $feature_key = '' ) {
			$tier          = self::wordform_get_product_tier();
			$license_state = self::wordform_get_license_state();
			$available     = self::wordform_is_feature_available( $feature_key );
			$message       = __( 'This feature is available in the current WordForm Pro build.', 'wordform-pro' );

			if ( 'pro' !== $tier ) {
				$message = __( 'This feature is reserved for the premium build.', 'wordform-pro' );
			} elseif ( self::wordform_enforce_license_limits() && 'active' !== $license_state ) {
				$message = __( 'This feature is currently restricted because the premium license is not active.', 'wordform-pro' );
			}

			return array(
				'feature'      => sanitize_key( $feature_key ),
				'available'    => $available,
				'limited'      => self::wordform_is_feature_limited( $feature_key ),
				'limits'       => self::wordform_get_feature_limits( $feature_key ),
				'tier'         => $tier,
				'licenseState' => $license_state,
				'message'      => $message,
			);
		}

		/**
		 * Central upgrade URL for free/basic surfaces.
		 *
		 * @return string
		 */
		public static function wordform_get_upgrade_url() {
			$upgrade_url = defined( 'SFTCY_WORDFORM_PRODUCT_URL' ) ? SFTCY_WORDFORM_PRODUCT_URL : 'https://softcoy.com/products/wordform-pro';
			return esc_url_raw( apply_filters( 'wordform_upgrade_url', $upgrade_url ) );
		}

		/**
		 * Shared short upgrade label.
		 *
		 * @return string
		 */
		public static function wordform_get_upgrade_cta_label() {
			return apply_filters( 'wordform_upgrade_cta_label', __( 'Get Pro', 'wordform' ) );
		}

		/**
		 * Builder element -> feature flag map.
		 *
		 * @return array
		 */
		public static function wordform_get_builder_element_feature_map() {
			return array(
				'upload'         => 'upload',
				'date'           => 'date',
				'datetime'       => 'datetime',
				'time'           => 'time',
				'tel'            => 'tel',
				'email'          => 'email',
				'rating'         => 'rating',
				'captcha'        => 'numeric_captcha',
				'hcaptcha'       => 'hcaptcha',
				'gcaptcha'       => 'google_recaptcha',
				'likert'         => 'likert',
				'signature'      => 'signature',
				'richeditor'     => 'richeditor',
				'payment_coupon' => 'payment_coupon',
				'stripe'         => 'stripe_gateway',
				'paypal'         => 'paypal_gateway',
				'square'         => 'square_gateway',
				'authorizenet'   => 'authorizenet_gateway',
			);
		}

		/**
		 * Whether a builder element is available in the current tier.
		 *
		 * @param string $element_type Builder element type.
		 * @return bool
		 */
		public static function wordform_is_builder_element_available( $element_type = '' ) {
			$element_type = sanitize_key( $element_type );
			$map          = self::wordform_get_builder_element_feature_map();

			if ( empty( $element_type ) || empty( $map[ $element_type ] ) ) {
				return true;
			}

			return self::wordform_is_feature_available( $map[ $element_type ] );
		}

		/**
		 * Connection app -> feature flag map.
		 *
		 * @return array
		 */
		public static function wordform_get_connect_application_feature_map() {
			return array(
				'customwebhook'  => 'custom_webhook',
				'googlesheet'    => 'google_sheets',
				'googlecalendar' => 'google_calendar',
				'zapier'         => 'zapier',
				'slack'          => 'slack',
				'make'           => 'make',
				'mailchimp'      => 'mailchimp',
				'mailerlite'     => 'mailerlite',
				'brevo'          => 'brevo',
				'airtable'       => 'airtable',
				'hubspot'        => 'hubspot',
				'activecampaign' => 'activecampaign',
				'salesforce'     => 'salesforce',
				'zohocrm'        => 'zohocrm',
			);
		}

		/**
		 * Whether a connection app is available in the current tier.
		 *
		 * @param string $application_slug App slug.
		 * @return bool
		 */
		public static function wordform_is_connect_application_available( $application_slug = '' ) {
			$application_slug = sanitize_key( $application_slug );
			$map              = self::wordform_get_connect_application_feature_map();

			if ( empty( $application_slug ) || empty( $map[ $application_slug ] ) ) {
				return true;
			}

			return self::wordform_is_feature_available( $map[ $application_slug ] );
		}

		/**
		 * Supported starter template IDs for the current tier.
		 *
		 * @return array
		 */
		public static function wordform_get_supported_template_ids() {
			if ( 'basic' !== self::wordform_get_product_tier() ) {
				return array();
			}

			return array(
				'contact_form',
				'appointment_booking',
				'customer_feedback',
				'product_survey',
				'simple_payment_form',
				'multi_step_registration',
			);
		}
	}
}
