<?php
/**
 * Shois Chat Button — Display Rules Engine
 *
 * Evaluates whether the widget should be shown on the current page
 * based on user-defined rules (page type, URL, post type, etc.).
 *
 * @package ShoisChatButton
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class SHCB_Display_Rules
 *
 * Evaluates display rules to determine widget visibility.
 */
class SHCB_Display_Rules {

	/**
	 * Check if widget should display on the current page.
	 *
	 * @return bool True if widget should be shown.
	 */
	public static function should_display() {
		$rules = get_option( 'shcb_display_rules', array() );

		if ( empty( $rules ) || empty( $rules['rules'] ) ) {
			return true; // No rules = show everywhere.
		}

		$mode  = isset( $rules['mode'] ) ? $rules['mode'] : 'show';
		$items = isset( $rules['rules'] ) ? $rules['rules'] : array();

		$has_include = false;
		$is_included = false;
		$is_excluded = false;

		foreach ( $items as $rule ) {
			if ( empty( $rule['enabled'] ) ) {
				continue;
			}

			// Legacy support: map global mode to individual rule match type if 'match' is missing.
			$match = isset( $rule['match'] ) ? $rule['match'] : ( 'hide' === $mode ? 'exclude' : 'include' );

			if ( 'include' === $match ) {
				$has_include = true;
				if ( self::evaluate_rule( $rule ) ) {
					$is_included = true;
				}
			} elseif ( 'exclude' === $match ) {
				if ( self::evaluate_rule( $rule ) ) {
					$is_excluded = true;
				}
			}
		}

		// Calculate final visibility.
		$visible = true;

		// If there are explicit 'include' rules, the page must match at least one to be shown.
		if ( $has_include && ! $is_included ) {
			$visible = false;
		}

		// 'exclude' rules always override 'include' rules.
		if ( $is_excluded ) {
			$visible = false;
		}

		return $visible;
	}

	/**
	 * Evaluate a single display rule.
	 *
	 * @param array $rule Rule configuration.
	 * @return bool True if the rule matches current page.
	 */
	private static function evaluate_rule( $rule ) {
		$type  = isset( $rule['type'] ) ? sanitize_key( $rule['type'] ) : '';
		$value = isset( $rule['value'] ) ? sanitize_text_field( $rule['value'] ) : '';

		switch ( $type ) {
			case 'entire_site':
				return true;

			case 'front_page':
				return is_front_page();

			case 'blog_page':
				return is_home();

			case 'all_posts':
				return is_singular( 'post' );

			case 'all_pages':
				return is_singular( 'page' );

			case 'specific_page':
				return is_page( absint( $value ) );

			case 'specific_post':
				return is_single( absint( $value ) );

			case 'post_type':
				return is_singular( $value );

			case 'category':
				if ( is_singular( 'post' ) ) {
					return has_category( $value );
				}
				return is_category( $value );

			case 'tag':
				if ( is_singular( 'post' ) ) {
					return has_tag( $value );
				}
				return is_tag( $value );

			case 'archive':
				return is_archive();

			case 'search':
				return is_search();

			case '404':
				return is_404();

			case 'url_contains':
				if ( ! empty( $value ) ) {
					$current = self::get_current_url();
					return ( false !== strpos( $current, $value ) );
				}
				return false;

			case 'url_exact':
				if ( ! empty( $value ) ) {
					$current = self::get_current_url();
					return ( untrailingslashit( $current ) === untrailingslashit( $value ) );
				}
				return false;

			case 'url_starts_with':
				if ( ! empty( $value ) ) {
					$current = self::get_current_url();
					return ( 0 === strpos( $current, $value ) );
				}
				return false;

			case 'woo_shop':
				if ( function_exists( 'is_shop' ) ) {
					return is_shop();
				}
				return false;

			case 'woo_product':
				if ( function_exists( 'is_product' ) ) {
					return is_product();
				}
				return false;

			case 'woo_cart':
				if ( function_exists( 'is_cart' ) ) {
					return is_cart();
				}
				return false;

			case 'woo_checkout':
				if ( function_exists( 'is_checkout' ) ) {
					return is_checkout();
				}
				return false;

			case 'woo_category':
				if ( function_exists( 'is_product_category' ) ) {
					return is_product_category( $value );
				}
				return false;

			case 'user_logged_in':
				return is_user_logged_in();

			case 'user_logged_out':
				return ! is_user_logged_in();

			case 'user_role':
				if ( is_user_logged_in() ) {
					$user = wp_get_current_user();
					return in_array( $value, (array) $user->roles, true );
				}
				return false;

			case 'device_mobile':
				return wp_is_mobile();

			case 'device_desktop':
				return ! wp_is_mobile();

			default:
				return false;
		}
	}

	/**
	 * Get the current page URL.
	 *
	 * @return string Current URL.
	 */
	private static function get_current_url() {
		$protocol = is_ssl() ? 'https' : 'http';
		$host     = isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : '';
		$uri      = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';

		return $protocol . '://' . $host . $uri;
	}

	/**
	 * Get all available rule types for the admin UI.
	 *
	 * @return array Grouped rule types.
	 */
	public static function get_rule_types() {
		$types = array(
			'general' => array(
				'label' => __( 'General', 'shois-chat-button' ),
				'rules' => array(
					array(
						'type'  => 'entire_site',
						'label' => __( 'Entire Site', 'shois-chat-button' ),
						'has_value' => false,
					),
					array(
						'type'  => 'front_page',
						'label' => __( 'Front Page', 'shois-chat-button' ),
						'has_value' => false,
					),
					array(
						'type'  => 'blog_page',
						'label' => __( 'Blog Page', 'shois-chat-button' ),
						'has_value' => false,
					),
					array(
						'type'  => 'all_posts',
						'label' => __( 'All Posts', 'shois-chat-button' ),
						'has_value' => false,
					),
					array(
						'type'  => 'all_pages',
						'label' => __( 'All Pages', 'shois-chat-button' ),
						'has_value' => false,
					),
					array(
						'type'  => 'archive',
						'label' => __( 'Archive Pages', 'shois-chat-button' ),
						'has_value' => false,
					),
					array(
						'type'  => 'search',
						'label' => __( 'Search Results', 'shois-chat-button' ),
						'has_value' => false,
					),
					array(
						'type'  => '404',
						'label' => __( '404 Page', 'shois-chat-button' ),
						'has_value' => false,
					),
				),
			),
			'specific' => array(
				'label' => __( 'Specific', 'shois-chat-button' ),
				'rules' => array(
					array(
						'type'  => 'specific_page',
						'label' => __( 'Specific Page', 'shois-chat-button' ),
						'has_value' => true,
						'value_type' => 'page_select',
					),
					array(
						'type'  => 'specific_post',
						'label' => __( 'Specific Post', 'shois-chat-button' ),
						'has_value' => true,
						'value_type' => 'post_select',
					),
					array(
						'type'  => 'post_type',
						'label' => __( 'Post Type', 'shois-chat-button' ),
						'has_value' => true,
						'value_type' => 'text',
					),
					array(
						'type'  => 'category',
						'label' => __( 'Category', 'shois-chat-button' ),
						'has_value' => true,
						'value_type' => 'text',
					),
					array(
						'type'  => 'tag',
						'label' => __( 'Tag', 'shois-chat-button' ),
						'has_value' => true,
						'value_type' => 'text',
					),
				),
			),
			'url' => array(
				'label' => __( 'URL', 'shois-chat-button' ),
				'rules' => array(
					array(
						'type'  => 'url_contains',
						'label' => __( 'URL Contains', 'shois-chat-button' ),
						'has_value' => true,
						'value_type' => 'text',
					),
					array(
						'type'  => 'url_exact',
						'label' => __( 'URL Exact Match', 'shois-chat-button' ),
						'has_value' => true,
						'value_type' => 'text',
					),
					array(
						'type'  => 'url_starts_with',
						'label' => __( 'URL Starts With', 'shois-chat-button' ),
						'has_value' => true,
						'value_type' => 'text',
					),
				),
			),
			'woocommerce' => array(
				'label' => __( 'WooCommerce', 'shois-chat-button' ),
				'rules' => array(
					array(
						'type'  => 'woo_shop',
						'label' => __( 'Shop Page', 'shois-chat-button' ),
						'has_value' => false,
					),
					array(
						'type'  => 'woo_product',
						'label' => __( 'Product Pages', 'shois-chat-button' ),
						'has_value' => false,
					),
					array(
						'type'  => 'woo_cart',
						'label' => __( 'Cart Page', 'shois-chat-button' ),
						'has_value' => false,
					),
					array(
						'type'  => 'woo_checkout',
						'label' => __( 'Checkout Page', 'shois-chat-button' ),
						'has_value' => false,
					),
					array(
						'type'  => 'woo_category',
						'label' => __( 'Product Category', 'shois-chat-button' ),
						'has_value' => true,
						'value_type' => 'text',
					),
				),
			),
			'user' => array(
				'label' => __( 'User', 'shois-chat-button' ),
				'rules' => array(
					array(
						'type'  => 'user_logged_in',
						'label' => __( 'Logged In Users', 'shois-chat-button' ),
						'has_value' => false,
					),
					array(
						'type'  => 'user_logged_out',
						'label' => __( 'Logged Out Users', 'shois-chat-button' ),
						'has_value' => false,
					),
					array(
						'type'  => 'user_role',
						'label' => __( 'User Role', 'shois-chat-button' ),
						'has_value' => true,
						'value_type' => 'text',
					),
				),
			),
			'device' => array(
				'label' => __( 'Device', 'shois-chat-button' ),
				'rules' => array(
					array(
						'type'  => 'device_mobile',
						'label' => __( 'Mobile Only', 'shois-chat-button' ),
						'has_value' => false,
					),
					array(
						'type'  => 'device_desktop',
						'label' => __( 'Desktop Only', 'shois-chat-button' ),
						'has_value' => false,
					),
				),
			),
		);

		return $types;
	}
}
