<?php
/**
 * DevDiggers Plugins API Class
 *
 * @author DevDiggers
 * @version 1.0.0
 * @package DevDiggers\Framework
 */

defined( 'ABSPATH' ) || exit();

if ( ! class_exists( 'DDFW_Plugins_API' ) ) {
	/**
	 * Class for handling DevDiggers plugins API
	 */
	class DDFW_Plugins_API {
		/**
		 * The single instance of the class.
		 *
		 * @var DDFW_Plugins_API
		 */
		private static $instance;
		
		/**
		 * API base URL
		 */
		private $api_base_url = 'https://devdiggers.com/wp-json/ddwcs/v1';
		
		/**
		 * Cache key prefix
		 */
		private $cache_prefix = 'ddfw_plugins_';
		
		/**
		 * Cache expiry time (1 hour)
		 */
		private $cache_expiry = 3600;
		
		/**
		 * Singleton implementation.
		 *
		 * @return DDFW_Plugins_API
		 */
		public static function instance() {
			return ! is_null( self::$instance ) ? self::$instance : new self();
		}

		/**
		 * Constructor
		 */
		public function __construct() {
			// Initialize hooks
			add_action( 'wp_ajax_ddfw_refresh_plugins_cache', [ $this, 'ajax_refresh_plugins_cache' ] );
		}

		/**
		 * Get all plugins from website
		 * 
		 * @return array
		 */
		public function get_website_plugins() {
			$cache_key   = $this->cache_prefix . 'website_plugins';
			$cached_data = get_transient( $cache_key );

			if ( $cached_data !== false ) {
				return $cached_data;
			}

			// Try to fetch from API
			$plugins_data = $this->fetch_plugins_from_api();

			if ( $plugins_data && isset( $plugins_data['plugins'] ) ) {
				set_transient( $cache_key, $plugins_data['plugins'], $this->cache_expiry );
				return $plugins_data['plugins'];
			}

			// Fallback to local data if API fails
			return $this->get_fallback_plugins_data();
		}

		/**
		 * Get featured plugins
		 * 
		 * @return array
		 */
		public function get_featured_plugins() {
			$cache_key = $this->cache_prefix . 'featured_plugins';
			$cached_data = get_transient( $cache_key );
			
			if ( $cached_data !== false ) {
				return $cached_data;
			}
			
			// Try to fetch from API
			$response = wp_remote_get( $this->api_base_url . '/plugins/featured' );
			
			if ( ! is_wp_error( $response ) && wp_remote_retrieve_response_code( $response ) === 200 ) {
				$featured_plugins = json_decode( wp_remote_retrieve_body( $response ), true );
				set_transient( $cache_key, $featured_plugins, $this->cache_expiry );
				return $featured_plugins;
			}
			
			// Fallback to first 4 plugins
			$all_plugins = $this->get_website_plugins();
			$featured_plugins = array_slice( $all_plugins, 0, 4 );
			set_transient( $cache_key, $featured_plugins, $this->cache_expiry );
			
			return $featured_plugins;
		}

		/**
		 * Get plugin statistics
		 * 
		 * @return array
		 */
		public function get_plugin_statistics() {
			$cache_key = $this->cache_prefix . 'statistics';
			$cached_data = get_transient( $cache_key );
			
			if ( $cached_data !== false ) {
				return $cached_data;
			}
			
			// Try to fetch from API
			$plugins_data = $this->fetch_plugins_from_api();
			
			if ( $plugins_data && isset( $plugins_data['stats'] ) ) {
				set_transient( $cache_key, $plugins_data['stats'], $this->cache_expiry );
				return $plugins_data['stats'];
			}

			// Fallback statistics
			$all_plugins = $this->get_website_plugins();
			$stats = [
				'total_plugins' => count( $all_plugins ),
				'active_plugins' => count( array_filter( $all_plugins, function( $plugin ) {
					return $plugin['status'] === 'active';
				} ) ),
				'available_plugins' => count( array_filter( $all_plugins, function( $plugin ) {
					return $plugin['status'] === 'available';
				} ) ),
				'average_rating' => 4.9,
				'total_sales' => 2000
			];

			set_transient( $cache_key, $stats, $this->cache_expiry );
			return $stats;
		}

		/**
		 * Fetch plugins from API
		 * 
		 * @return array|false
		 */
		private function fetch_plugins_from_api() {
			$response = wp_remote_get( $this->api_base_url . '/plugins', [
				'timeout' => 30,
				'headers' => [
					'User-Agent' => 'DevDiggers Framework/' . DDFW_SCRIPT_VERSION
				]
			] );

			if ( is_wp_error( $response ) ) {
				return false;
			}

			$response_code = wp_remote_retrieve_response_code( $response );
			if ( $response_code !== 200 ) {
				return false;
			}

			$body = wp_remote_retrieve_body( $response );
			return json_decode( $body, true );
		}

		/**
		 * Get fallback plugins data
		 * 
		 * @return array
		 */
		private function get_fallback_plugins_data() {
			return [
				[
					'id' => 'multipos-pos-system',
					'name' => 'MultiPOS – Point of Sale (POS System)',
					'slug' => 'multipos-pos-system',
					'description' => 'Turn your store into a unified shopping destination where in-person transactions meet eCommerce efficiency.',
					'version' => '2.1.0',
					'price' => '$89',
					'rating' => 4.9,
					'sales' => '500+',
					'category' => 'Point of Sale',
					'features' => ['Real-time Sync', 'Inventory Management', 'Receipt Printing', 'Multi-location Support'],
					'image' => 'https://devdiggers.com/wp-content/uploads/2024/multipos-featured.jpg',
					'url' => 'https://devdiggers.com/woocommerce-extensions/multipos-point-of-sale-pos-system/',
					'status' => 'active',
					'last_updated' => '2024-12-15'
				],
				[
					'id' => 'product-view-ar',
					'name' => 'WooCommerce Product View in AR | 3D Augmented Reality View',
					'slug' => 'product-view-ar',
					'description' => 'Bring your products to life so shoppers can visualize them before they buy.',
					'version' => '1.8.0',
					'price' => '$79',
					'rating' => 4.8,
					'sales' => '300+',
					'category' => 'Product Display',
					'features' => ['3D AR View', 'Mobile Optimized', 'Easy Setup', 'Multiple Formats'],
					'image' => 'https://devdiggers.com/wp-content/uploads/2024/ar-view-featured.jpg',
					'url' => 'https://devdiggers.com/woocommerce-extensions/woocommerce-product-view-in-ar-3d-augmented-reality-view/',
					'status' => 'active',
					'last_updated' => '2024-12-10'
				],
				[
					'id' => 'biometric-login',
					'name' => 'WooCommerce Biometric Login',
					'slug' => 'biometric-login',
					'description' => 'Secure biometric authentication for WooCommerce customers using fingerprint, face ID, and more.',
					'version' => '1.5.0',
					'price' => '$69',
					'rating' => 4.7,
					'sales' => '200+',
					'category' => 'Security',
					'features' => ['Fingerprint Login', 'Face ID Support', 'Secure Authentication', 'Mobile Compatible'],
					'image' => 'https://devdiggers.com/wp-content/uploads/2024/biometric-featured.jpg',
					'url' => 'https://devdiggers.com/woocommerce-extensions/woocommerce-biometric-login/',
					'status' => 'active',
					'last_updated' => '2024-12-08'
				],
				[
					'id' => 'woocommerce-affiliates',
					'name' => 'WooCommerce Affiliates – Boost Your Earnings with Affiliate Marketing',
					'slug' => 'woocommerce-affiliates',
					'description' => 'Build bridges between your products and a vast network of potential promoters.',
					'version' => '2.3.0',
					'price' => '$99',
					'rating' => 4.9,
					'sales' => '400+',
					'category' => 'Marketing',
					'features' => ['Commission Management', 'Referral Tracking', 'Payout System', 'Analytics Dashboard'],
					'image' => 'https://devdiggers.com/wp-content/uploads/2024/affiliates-featured.jpg',
					'url' => 'https://devdiggers.com/woocommerce-extensions/woocommerce-affiliates-boost-your-earnings-with-affiliate-marketing/',
					'status' => 'active',
					'last_updated' => '2024-12-12'
				],
				[
					'id' => 'wallet-management',
					'name' => 'WooCommerce Wallet Management',
					'slug' => 'wallet-management',
					'description' => 'Lets customers deposit funds and use the balance for future purchases, streamlining payments.',
					'version' => '1.9.0',
					'price' => '$79',
					'rating' => 4.8,
					'sales' => '350+',
					'category' => 'Payment',
					'features' => ['Digital Wallet', 'Easy Deposits', 'Secure Transactions', 'Balance Management'],
					'image' => 'https://devdiggers.com/wp-content/uploads/2024/wallet-featured.jpg',
					'url' => 'https://devdiggers.com/woocommerce-extensions/woocommerce-wallet-management/',
					'status' => 'active',
					'last_updated' => '2024-12-14'
				],
				[
					'id' => 'points-rewards',
					'name' => 'WooCommerce Points and Rewards',
					'slug' => 'points-rewards',
					'description' => 'Boost customer loyalty with a comprehensive points and rewards system for your WooCommerce store.',
					'version' => '1.0.0',
					'price' => '$89',
					'rating' => 4.9,
					'sales' => '150+',
					'category' => 'Loyalty',
					'features' => ['Points System', 'Reward Management', 'Customer Engagement', 'Analytics'],
					'image' => 'https://devdiggers.com/wp-content/uploads/2024/points-rewards-featured.jpg',
					'url' => 'https://devdiggers.com/woocommerce-extensions/woocommerce-points-and-rewards/',
					'status' => 'available',
					'last_updated' => '2024-12-20'
				]
			];
		}

		/**
		 * Check if plugin is installed locally
		 * 
		 * @param string $plugin_slug
		 * @return array|false
		 */
		public function is_plugin_installed( $plugin_slug ) {
			$installed_plugins = get_plugins();
			$active_plugins = get_option( 'active_plugins', [] );

			foreach ( $installed_plugins as $plugin_file => $plugin_data ) {
				if ( strpos( $plugin_file, $plugin_slug ) !== false || 
					strpos( $plugin_data['Name'], 'DevDiggers' ) !== false ) {
					return [
						'installed' => true,
						'active' => in_array( $plugin_file, $active_plugins ),
						'plugin_file' => $plugin_file,
						'plugin_data' => $plugin_data
					];
				}
			}

			return false;
		}

		/**
		 * Refresh plugins cache
		 * 
		 * @return array
		 */
		public function refresh_plugins_cache() {
			// Clear all caches
			delete_transient( $this->cache_prefix . 'website_plugins' );
			delete_transient( $this->cache_prefix . 'featured_plugins' );
			delete_transient( $this->cache_prefix . 'statistics' );

			// Fetch fresh data
			$plugins = $this->get_website_plugins();
			$featured = $this->get_featured_plugins();
			$stats = $this->get_plugin_statistics();

			return [
				'success' => true,
				'message' => 'Plugins cache refreshed successfully',
				'data' => [
					'plugins' => $plugins,
					'featured' => $featured,
					'stats' => $stats
				]
			];
		}

		/**
		 * AJAX handler for refreshing cache
		 */
		public function ajax_refresh_plugins_cache() {
			check_ajax_referer( 'ddfw-nonce', 'nonce' );

			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( 'Insufficient permissions' );
			}

			$result = $this->refresh_plugins_cache();
			wp_send_json_success( $result );
		}
	}
}

// Initialize the class
DDFW_Plugins_API::instance();
