<?php
defined('ABSPATH') || exit;

if ( ! class_exists( 'SRFW_Front' ) ) :
	
	class SRFW_Front {

		public function __construct() {
			add_action('template_redirect', array($this, 'srfw_hide_restricted_product_on_single_page'));
			add_action('pre_get_posts', array($this, 'srfw_hide_restricted_products_and_categories'));
			add_filter('woocommerce_product_is_visible', array($this, 'srfw_filter_product_visible'), 10, 2);
			add_filter('woocommerce_is_purchasable', array($this, 'srfw_filter_purchasable'), 10, 2);
			add_filter('woocommerce_add_to_cart_validation', array($this, 'srfw_add_to_cart_validation'), 10, 3);
		}

		private function srfw_compute_restrictions() {
			if (current_user_can('administrator')) {
				return array('products' => array(), 'categories' => array());
			}
			$restricted_cats = array();
			$restricted_products = array();
			
			// Check global settings first
			$global_settings = $this->srfw_get_global_settings();
			if ($global_settings) {
				$restricted_cats = $global_settings['selectedCategories'];
				$restricted_products = $global_settings['selectedProducts'];
			}
			
			// Check role-based restrictions
			$role_restrictions = $this->srfw_get_current_user_restrictions();
			if ($role_restrictions) {
				$restricted_cats = array_unique(array_merge($restricted_cats, $role_restrictions['selectedCategories']));
				$restricted_products = array_unique(array_merge($restricted_products, $role_restrictions['selectedProducts']));
			}
			
			$country_restrictions = $this->srfw_get_country_restrictions();
			if ($country_restrictions) {
				$restricted_cats = array_unique(array_merge($restricted_cats, $country_restrictions['selectedCategories']));
				$restricted_products = array_unique(array_merge($restricted_products, $country_restrictions['selectedProducts']));
			}

			return array('products' => array_filter(array_map('absint', $restricted_products)), 'categories' => array_filter(array_map('absint', $restricted_cats)));
		}

		private function srfw_is_product_restricted($product_id) {
			$sets = $this->srfw_compute_restrictions();
			if (in_array($product_id, $sets['products'], true)) {
				return true;
			}
			if (empty($sets['categories'])) { return false; }
			$product = wc_get_product($product_id);
			if (!$product) { return false; }
			$cat_ids = $product->get_category_ids();
			if (array_intersect($cat_ids, $sets['categories'])) { return true; }
			return false;
		}

		public function srfw_filter_product_visible($visible, $product_id) {
			return $visible && ! $this->srfw_is_product_restricted($product_id) ? $visible : false;
		}

		public function srfw_filter_purchasable($purchasable, $product) {
			if ($this->srfw_is_product_restricted($product->get_id())) { return false; }
			return $purchasable;
		}

		public function srfw_add_to_cart_validation($valid, $product_id, $quantity) {
			if ($this->srfw_is_product_restricted($product_id)) {
				wc_add_notice(__('This product is not available for your account.', 'store-restriction-for-woocommerce'), 'error');
				return false;
			}
			return $valid;
		}

		/**
		 * Get global-based restriction settings
		 */
		private function srfw_get_global_settings() {
			$settings = get_option( 'srfw_global_settings', array() );
			if ( empty( $settings ) || empty( $settings['enabled'] ) ) {
				return false;
			}
			return $settings;
		}

		private function srfw_get_user_country() {

			if ( class_exists( 'WC_Geolocation' ) ) {

				$geo      = new WC_Geolocation(); 
				$user_ip  = $geo->get_ip_address();
				$user_geo = $geo->geolocate_ip( $user_ip );
				$country  = $user_geo['country']; 
				if (!empty($user_geo['country'])) {
					return $user_geo['country'];
				}

			}
			return false; 

		}

		/**
		 * Get country-based restrictions if enabled
		 */
		private function srfw_get_country_restrictions() {
			$user_country = $this->srfw_get_user_country();
			
			if (!$user_country) {
				return false;
			}

			$country_settings = get_option('srfw_country_settings', array());
			if (isset($country_settings[$user_country]) && $country_settings[$user_country]['enabled']) {
				return $country_settings[$user_country];
			}
			return false;
		}

		public function srfw_hide_restricted_product_on_single_page() {
			if (current_user_can('administrator')) {
				return;
			}

			if (is_singular('product')) {
				global $post;

				$sets = $this->srfw_compute_restrictions();
				if (in_array($post->ID, $sets['products'], true)) {
					wp_safe_redirect(home_url());
					exit;
				}
				if (!empty($sets['categories'])) {
					$categories = get_the_terms($post->ID, 'product_cat');
					if ($categories && !is_wp_error($categories)) {
						$category_ids = wp_list_pluck($categories, 'term_id');
						$intersect = array_intersect($category_ids, $sets['categories']);

						if (!empty($intersect)) {
							wp_safe_redirect(home_url());
							exit;
						}
					}
				}
			}
		}

		/**
		 * Get current user restrictions based on role
		 */
		private function srfw_get_current_user_restrictions() {
			$current_user = wp_get_current_user();
			$user_roles = $current_user->roles;
			$role_settings = get_option('srfw_role_settings', array());
			foreach ($user_roles as $role) {
				if (isset($role_settings[$role]) && $role_settings[$role]['enabled']) {
					return $role_settings[$role];
				}
			}
			return false;
		}

		public function srfw_hide_restricted_products_and_categories($query) {
			if (!is_admin() && $query->is_main_query()) {
				if (current_user_can('administrator')) {
					return;
				}
				$sets = $this->srfw_compute_restrictions();
				if (!empty($sets['products'])) {
					$existing_not_in = $query->get('post__not_in', array());
					$merged_not_in = array_unique(array_merge($existing_not_in, $sets['products']));
					$query->set('post__not_in', $merged_not_in);
				}
				if (!empty($sets['categories'])) {
					$tax_query = $query->get('tax_query', array());
					if (!is_array($tax_query)) {
						$tax_query = array();
					}
					$tax_query[] = array(
						'taxonomy' => 'product_cat',
						'field'    => 'term_id',
						'terms'    => $sets['categories'],
						'operator' => 'NOT IN',
					);
					$query->set('tax_query', $tax_query);
				}
			}
		}
		
	}

	new SRFW_Front();

endif;