<?php

namespace WPKIN_SHOP_MANAGER;

use WPKIN_SHOP_MANAGER\Modules\CustomerTagger;
use WPKIN_SHOP_MANAGER\Modules\InsightEngine;
use WPKIN_SHOP_MANAGER\Modules\EmployeeManager;

if ( ! defined( 'ABSPATH' ) ) {
	wp_die( esc_html__( 'You can\'t access this page', 'shop-manager' ) );
}

/**
 * Modules Handler Class
 *
 * @since 1.0.0
 */
class Modules {

	/**
	 * Modules class constructor
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		CustomerTagger::init();
		EmployeeManager::init();

		// Clear insight cache when orders change
		add_action( 'woocommerce_new_order',            [ InsightEngine::class, 'clear_cache' ] );
		add_action( 'woocommerce_order_status_changed', [ InsightEngine::class, 'clear_cache' ] );

		// Clear insight cache when product stock changes
		add_action( 'woocommerce_product_set_stock',         [ InsightEngine::class, 'clear_cache' ] );
		add_action( 'woocommerce_variation_set_stock',       [ InsightEngine::class, 'clear_cache' ] );
		add_action( 'woocommerce_product_set_stock_status',  [ InsightEngine::class, 'clear_cache' ] );
		add_action( 'save_post_product',                     [ InsightEngine::class, 'clear_cache' ] );

		// Merge saved excluded roles into the filter so all usages respect settings
		add_filter( 'wpkin_sm_exclude_customer_roles', [ $this, 'merge_excluded_roles' ] );
	}

	/**
	 * Merge saved excluded roles from settings into the default list.
	 */
	public function merge_excluded_roles( array $roles ): array {
		$settings       = get_option( 'wpkin_sm_admin_settings', [] );
		$saved_excluded = $settings['customer_tagging']['excluded_roles'] ?? null;
		if ( $saved_excluded !== null ) {
			return array_values( array_map( 'sanitize_text_field', $saved_excluded ) );
		}
		return $roles;
	}
}
