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

if ( ! class_exists( 'SRFW_Register' ) ) :

	class SRFW_Register {

		public function __construct() {
			add_action( 'admin_enqueue_scripts', array( $this, 'srfw_scripts' ) );
			add_action('rest_api_init', array( $this, 'srfw_register_routes' ));
			add_action('admin_init', array( $this, 'init' ));
		}

		public function srfw_register_routes() {
			$cap = function() { return current_user_can('manage_woocommerce'); };
			register_rest_route('srfw/v1', '/settings/global', array(
				'methods' => 'POST',
				'callback' => array( $this, 'srfw_save_global_settings' ),
				'permission_callback' => $cap,
			));
			register_rest_route('srfw/v1', '/settings/get-saved-data', array(
				'methods' => 'GET',
				'callback' => array( $this, 'srfw_get_save_global_settings' ),
				'permission_callback' => $cap,
			));
			register_rest_route('srfw/v1', '/settings/role', array(
				'methods' => 'POST',
				'callback' => array( $this, 'srfw_save_role_settings' ),
				'permission_callback' => $cap,
			));
			register_rest_route('srfw/v1', '/settings/role/(?P<role>[a-zA-Z0-9_-]+)', array(
				'methods' => 'GET',
				'callback' => array( $this, 'srfw_get_role_settings' ),
				'permission_callback' => $cap,
			));
			register_rest_route('srfw/v1', '/settings/roles', array(
				'methods' => 'GET',
				'callback' => array( $this, 'srfw_list_role_settings' ),
				'permission_callback' => $cap,
			));
			register_rest_route('srfw/v1', '/settings/country', array(
				'methods' => 'POST',
				'callback' => array( $this, 'srfw_save_country_settings' ),
				'permission_callback' => $cap,
			));
			register_rest_route('srfw/v1', '/settings/country/(?P<country>[a-zA-Z0-9_-]+)', array(
				'methods' => 'GET',
				'callback' => array( $this, 'srfw_get_country_settings' ),
				'permission_callback' => $cap,
			));
			register_rest_route('srfw/v1', '/settings/countries', array(
				'methods' => 'GET',
				'callback' => array( $this, 'srfw_list_country_settings' ),
				'permission_callback' => $cap,
			));
			// Bulk role restrictions
			register_rest_route('srfw/v1', '/settings/roles/bulk', array(
				'methods' => 'POST',
				'callback' => array( $this, 'srfw_save_bulk_roles' ),
				'permission_callback' => $cap,
			));
			// Bulk country restrictions
			register_rest_route('srfw/v1', '/settings/countries/bulk', array(
				'methods' => 'POST',
				'callback' => array( $this, 'srfw_save_bulk_countries' ),
				'permission_callback' => $cap,
			));
			// Order-based settings (UI available; optional in free)
			register_rest_route('srfw/v1', '/settings/order', array(
				'methods' => 'POST',
				'callback' => array( $this, 'srfw_save_order_settings' ),
				'permission_callback' => $cap,
			));
			register_rest_route('srfw/v1', '/settings/order', array(
				'methods' => 'GET',
				'callback' => array( $this, 'srfw_get_order_settings' ),
				'permission_callback' => $cap,
			));
		}

		public function srfw_save_order_settings( WP_REST_Request $request ) {
			if ( ! current_user_can( 'manage_woocommerce' ) ) {
				return new WP_Error( 'forbidden', 'You do not have permission to do this.', array( 'status' => 403 ) );
			}

			$data = $request->get_json_params();
			if ( ! is_array( $data ) ) {
				return new WP_Error( 'invalid_data', 'Invalid data format', array( 'status' => 400 ) );
			}

			$sanitized = array(
				'enabled' => ! empty( $data['enabled'] ),
				'targetProducts' => isset( $data['targetProducts'] ) && is_array( $data['targetProducts'] ) ? array_map( 'absint', $data['targetProducts'] ) : array(),
				'targetCategories' => isset( $data['targetCategories'] ) && is_array( $data['targetCategories'] ) ? array_map( 'absint', $data['targetCategories'] ) : array(),
				'minTotalSpent' => isset( $data['minTotalSpent'] ) ? floatval( $data['minTotalSpent'] ) : 0,
				'minOrderCount' => isset( $data['minOrderCount'] ) ? absint( $data['minOrderCount'] ) : 0,
				'requiredProducts' => isset( $data['requiredProducts'] ) && is_array( $data['requiredProducts'] ) ? array_map( 'absint', $data['requiredProducts'] ) : array(),
			);

			update_option( 'srfw_order_settings', $sanitized );

			return rest_ensure_response( array( 'success' => true ) );
		}

		public function srfw_get_order_settings() {
			$defaults = array(
				'enabled' => false,
				'targetProducts' => array(),
				'targetCategories' => array(),
				'minTotalSpent' => 0,
				'minOrderCount' => 0,
				'requiredProducts' => array(),
			);
			$settings = get_option( 'srfw_order_settings', array() );
			return rest_ensure_response( wp_parse_args( $settings, $defaults ) );
		}

		public function srfw_save_bulk_roles( WP_REST_Request $request ) {
			$data = $request->get_json_params();
			if ( ! is_array( $data ) || empty( $data['roles'] ) || ! is_array( $data['roles'] ) ) {
				return new WP_Error('invalid_data', 'Invalid roles bulk payload', array('status'=>400));
			}
			$roles = array_map('sanitize_text_field', $data['roles']);
			$enabled = ! empty( $data['enabled'] );
			$products = isset($data['selectedProducts']) && is_array($data['selectedProducts']) ? array_map('absint', $data['selectedProducts']) : array();
			$categories = isset($data['selectedCategories']) && is_array($data['selectedCategories']) ? array_map('absint', $data['selectedCategories']) : array();
			$all_role_settings = get_option('srfw_role_settings', array());
			foreach ( $roles as $role_key ) {
				$all_role_settings[$role_key] = array(
					'enabled' => $enabled,
					'selectedProducts' => $products,
					'selectedCategories' => $categories,
				);
			}
			update_option('srfw_role_settings', $all_role_settings);
			return rest_ensure_response(array('success'=>true,'updatedRoles'=>$roles));
		}

		public function srfw_save_bulk_countries( WP_REST_Request $request ) {
			$data = $request->get_json_params();
			if ( ! is_array( $data ) || empty( $data['countries'] ) || ! is_array( $data['countries'] ) ) {
				return new WP_Error('invalid_data', 'Invalid countries bulk payload', array('status'=>400));
			}
			$countries = array_map('sanitize_text_field', $data['countries']);
			$enabled = ! empty( $data['enabled'] );
			$products = isset($data['selectedProducts']) && is_array($data['selectedProducts']) ? array_map('absint', $data['selectedProducts']) : array();
			$categories = isset($data['selectedCategories']) && is_array($data['selectedCategories']) ? array_map('absint', $data['selectedCategories']) : array();
			$all_country_settings = get_option('srfw_country_settings', array());
			foreach ( $countries as $country_code ) {
				$all_country_settings[$country_code] = array(
					'enabled' => $enabled,
					'selectedProducts' => $products,
					'selectedCategories' => $categories,
				);
			}
			update_option('srfw_country_settings', $all_country_settings);
			return rest_ensure_response(array('success'=>true,'updatedCountries'=>$countries));
		}

		public function srfw_list_role_settings() {
			$all_role_settings = get_option('srfw_role_settings', array());
			$summary = array();
			foreach ($all_role_settings as $role => $data) {
				$summary[] = array(
					'role' => $role,
					'enabled' => !empty($data['enabled']),
					'productCount' => isset($data['selectedProducts']) ? count($data['selectedProducts']) : 0,
					'categoryCount' => isset($data['selectedCategories']) ? count($data['selectedCategories']) : 0,
				);
			}
			return rest_ensure_response($summary);
		}

		public function srfw_list_country_settings() {
			$all_country_settings = get_option('srfw_country_settings', array());
			$summary = array();
			foreach ($all_country_settings as $code => $data) {
				$summary[] = array(
					'country' => $code,
					'enabled' => !empty($data['enabled']),
					'productCount' => isset($data['selectedProducts']) ? count($data['selectedProducts']) : 0,
					'categoryCount' => isset($data['selectedCategories']) ? count($data['selectedCategories']) : 0,
				);
			}
			return rest_ensure_response($summary);
		}

		public function srfw_get_save_global_settings() {

			$srfw_global_settings = get_option('srfw_global_settings', array());
			return rest_ensure_response($srfw_global_settings);
		}

		public function srfw_save_global_settings( WP_REST_Request $request ) {

			if (!current_user_can('manage_woocommerce')) {
				return new WP_Error('forbidden', 'You do not have permission to do this.', array( 'status' => 403 ));
			}

			$settings = $request->get_json_params();

			if (!is_array($settings)) {
				return new WP_Error('invalid_data', 'Invalid data format', array( 'status' => 400 ));
			}

			$sanitized = array(
				'enabled' => isset($settings['enabled']) ? (bool) $settings['enabled'] : false,
				'selectedProducts' => isset($settings['selectedProducts']) && is_array($settings['selectedProducts']) ? array_map('absint', $settings['selectedProducts']) : array(),
				'selectedCategories' => isset($settings['selectedCategories']) && is_array($settings['selectedCategories']) ? array_map('absint', $settings['selectedCategories']) : array(),
			);

			// update_option returns false if the value is unchanged, which
			// should still be considered a successful save from the API's perspective.
			$updated = update_option( 'srfw_global_settings', $sanitized );

			if ( false === $updated ) {
				// If unchanged, ensure the option exists and return success.
				$existing = get_option( 'srfw_global_settings', null );
				if ( null === $existing ) {
					add_option( 'srfw_global_settings', $sanitized );
				}
				return rest_ensure_response( array( 'success' => true, 'message' => 'Settings saved (no changes).' ) );
			}

			return rest_ensure_response( array( 'success' => true, 'message' => 'Settings saved successfully.' ) );
		}

		public function srfw_save_role_settings() {
			
			if (!current_user_can('manage_woocommerce')) {
				return new WP_Error('forbidden', 'You do not have permission to do this.', array( 'status' => 403 ));
			}

			// Get the request body
			$request_data = json_decode(file_get_contents('php://input'), true);

			// Validate the data
			if (!is_array($request_data)) {
				return new WP_Error('invalid_data', 'Invalid data format', array( 'status' => 400 ));
			}

			try {
				// Preserve global settings; do not delete when role restrictions enabled.

				// Save role-based settings
				$settings_to_save = array(
					'selectedRole' => sanitize_text_field($request_data['selectedRole']),
					'enabled' => (bool) $request_data['enabled'],
					'selectedProducts' => array_map('absint', $request_data['selectedProducts']),
					'selectedCategories' => array_map('absint', $request_data['selectedCategories'])
				);

				// Save settings for the specific role
				$all_role_settings = get_option('srfw_role_settings', array());
				$role_key = $settings_to_save['selectedRole'];
				
				// Update or add settings for this role
				$all_role_settings[ $role_key ] = array(
					'enabled' => $settings_to_save['enabled'],
					'selectedProducts' => $settings_to_save['selectedProducts'],
					'selectedCategories' => $settings_to_save['selectedCategories']
				);

				// Save all role settings
				update_option('srfw_role_settings', $all_role_settings);

				// Return success response
				return rest_ensure_response(array(
					'success' => true,
					'message' => 'Role settings saved successfully',
					'data' => $all_role_settings
				));

			} catch (Exception $e) {
				return new WP_Error('save_error', $e->getMessage(), array( 'status' => 500 ));
			}
		}

		public function srfw_get_role_settings( $request ) {
			$role = $request['role'];
			$all_role_settings = get_option('srfw_role_settings', array());
			
			if (isset($all_role_settings[ $role ])) {
				return rest_ensure_response(array(
					'selectedRole' => $role,
					'enabled' => $all_role_settings[ $role ]['enabled'] ?? false,
					'selectedProducts' => $all_role_settings[ $role ]['selectedProducts'] ?? array(),
					'selectedCategories' => $all_role_settings[ $role ]['selectedCategories'] ?? array(),
				));
			}
			
			return rest_ensure_response(array(
				'selectedRole' => $role,
				'enabled' => false,
				'selectedProducts' => array(),
				'selectedCategories' => array(),
			));
		}

		public function srfw_save_country_settings( WP_REST_Request $request ) {
			if (!current_user_can('manage_woocommerce')) {
				return new WP_Error('forbidden', 'You do not have permission to do this.', array( 'status' => 403 ));
			}

			$request_data = json_decode(file_get_contents('php://input'), true);

			if (!is_array($request_data)) {
				return new WP_Error('invalid_data', 'Invalid data format', array( 'status' => 400 ));
			}

			try {
				// Preserve global settings; do not delete when country restrictions enabled.

				$settings_to_save = array(
					'selectedCountry' => sanitize_text_field($request_data['selectedCountry']),
					'enabled' => (bool) $request_data['enabled'],
					'selectedProducts' => array_map('absint', $request_data['selectedProducts']),
					'selectedCategories' => array_map('absint', $request_data['selectedCategories'])
				);

				$all_country_settings = get_option('srfw_country_settings', array());
				$country_key = $settings_to_save['selectedCountry'];
				
				// Update or add settings for this country
				$all_country_settings[$country_key] = array(
					'enabled' => $settings_to_save['enabled'],
					'selectedProducts' => $settings_to_save['selectedProducts'],
					'selectedCategories' => $settings_to_save['selectedCategories']
				);

				// Save all country settings
				update_option('srfw_country_settings', $all_country_settings);

				return rest_ensure_response(array(
					'success' => true,
					'message' => 'Country settings saved successfully',
					'data' => $all_country_settings
				));

			} catch (Exception $e) {
				return new WP_Error('save_error', $e->getMessage(), array( 'status' => 500 ));
			}
		}

		public function srfw_get_country_settings( $request ) {
			$country = $request['country'];
			$all_country_settings = get_option('srfw_country_settings', array());
			
			if (isset($all_country_settings[$country])) {
				return rest_ensure_response(array(
					'selectedCountry' => $country,
					'enabled' => $all_country_settings[$country]['enabled'] ?? false,
					'selectedProducts' => $all_country_settings[$country]['selectedProducts'] ?? array(),
					'selectedCategories' => $all_country_settings[$country]['selectedCategories'] ?? array(),
				));
			}
			
			return rest_ensure_response(array(
				'selectedCountry' => $country,
				'enabled' => false,
				'selectedProducts' => array(),
				'selectedCategories' => array(),
			));
		}

		// WooCommerce settings tab integration
		public function srfw_settings_tab( $tabs ) {
			$tabs['srfw'] = __('Store Restriction', 'store-restriction-for-woocommerce');
			return $tabs;
		}

		public function srfw_settings_tab_content() {
			// Render the React app inside WooCommerce Settings tab
			wp_enqueue_script('srfw-script');
			echo '<div id="srfw-admin"></div>';
		}

		public function srfw_hooks_settings_tab() {
			add_filter('woocommerce_settings_tabs_array', array($this,'srfw_settings_tab'), 50);
			add_action('woocommerce_settings_tabs_srfw', array($this,'srfw_settings_tab_content'));
		}

		// Initialize settings tab hooks on admin_init
		public function init() {
			if ( is_admin() ) {
				$this->srfw_hooks_settings_tab();
			}
		}

		public function srfw_scripts() {

			wp_register_script('srfw-script', SRFW_URL . 'build/admin.bundle.js', array( 'wp-element' ), '1.0.0', true);

			$product_categories = get_terms(array(
				'taxonomy' => 'product_cat',
				'hide_empty' => false,
			));

			$products = wc_get_products(array(
				'status' => 'publish',
				'limit' => -1, 
			));

			$categories_data = array();
			if (!is_wp_error($product_categories)) {
				foreach ($product_categories as $category) {
					$categories_data[] = array(
						'id' => $category->term_id,
						'name' => $category->name,
						'slug' => $category->slug,
					);
				}
			}

			$products_data = array();
			foreach ($products as $product) {
				$products_data[] = array(
					'id' => $product->get_id(),
					'name' => $product->get_name(),
					'price' => $product->get_price(),
					'sku' => $product->get_sku(),
					'stock_status' => $product->get_stock_status(),
				);
			}

			global $wp_roles;
			$roles = array();
			if (!empty($wp_roles)) {
				foreach ($wp_roles->roles as $key => $role) {
					if ($key !== 'administrator') {
						$roles[] = array(
							'key' => $key,
							'name' => $role['name'],
						);
					}
				}
			}

			$wc_countries = new WC_Countries();
			$countries = $wc_countries->get_countries();
			$countries_data = array();
			foreach ($countries as $code => $name) {
				$countries_data[] = array(
					'code' => $code,
					'name' => $name
				);
			}

			$role_settings_existing = get_option('srfw_role_settings', array());
			$country_settings_existing = get_option('srfw_country_settings', array());
			$global_settings_existing = get_option('srfw_global_settings', array());

			wp_localize_script('srfw-script', 'SRFWAPP', array(
				'root' => esc_url_raw(rest_url()),
				'nonce' => wp_create_nonce('wp_rest'),
				'products' => $products_data,
				'categories' => $categories_data,
				'countries' => $countries_data, 
				'roles' => $roles,
				'roleSettingsSummary' => $role_settings_existing,
				'countrySettingsSummary' => $country_settings_existing,
				'globalSettings' => $global_settings_existing,
				'pluginUrl' => SRFW_URL,
				'assetsUrl' => SRFW_URL . 'src/admin/assets/',
			));
		}
	}

	new SRFW_Register();

endif;