<?php
/**
 * Pro: exclusion-based rule gating.
 *
 * The inverse of the free "include" filters already handled by the engine.
 * Any single exclusion match blocks the rule for this request.
 *
 * @package EasySearchReplace
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class ESRN_Pro_Exclusions {

	public static function register() {
		add_filter( 'esrn_should_apply_rule', array( __CLASS__, 'check' ), 10, 3 );
	}

	/**
	 * @param bool  $apply
	 * @param array $rule
	 * @param array $context
	 * @return bool
	 */
	public static function check( $apply, $rule, $context ) {
		if ( ! $apply ) {
			return false;
		}

		// Exclude by post type.
		$excl_types = isset( $rule['exclude_post_types'] ) && is_array( $rule['exclude_post_types'] ) ? $rule['exclude_post_types'] : array();
		if ( ! empty( $excl_types ) && ! empty( $context['post_type'] ) ) {
			if ( in_array( $context['post_type'], $excl_types, true ) ) {
				return false;
			}
		}

		// Exclude by post ID.
		$excl_ids = isset( $rule['exclude_post_ids'] ) ? (string) $rule['exclude_post_ids'] : '';
		if ( '' !== $excl_ids && ! empty( $context['post_id'] ) ) {
			$list = array_filter( array_map( 'intval', array_map( 'trim', explode( ',', $excl_ids ) ) ) );
			if ( in_array( (int) $context['post_id'], $list, true ) ) {
				return false;
			}
		}

		// Exclude by URL substring.
		$excl_urls = isset( $rule['exclude_urls'] ) ? (string) $rule['exclude_urls'] : '';
		if ( '' !== $excl_urls && ! empty( $context['url'] ) ) {
			$lines = array_filter( array_map( 'trim', explode( "\n", $excl_urls ) ) );
			foreach ( $lines as $needle ) {
				if ( '' !== $needle && false !== stripos( $context['url'], $needle ) ) {
					return false;
				}
			}
		}

		return true;
	}
}
