<?php
/**
 * @package Hafenstudios\Wellenbrecher
 */

namespace Hafenstudios\Wellenbrecher\Rules;

use Hafenstudios\Wellenbrecher\Engine\Context;
use Hafenstudios\Wellenbrecher\Engine\RuleResult;

defined( 'ABSPATH' ) || exit;

/**
 * Eigene Keyword-Liste des Betreibers (lists.custom_keywords, eine Zeile je
 * Begriff): einfache case-insensitive String-Matches gegen Inhalt,
 * Autor-Name und Autor-URL. Kein Nutzer-Regex in Free (Bauplan Kap. 11).
 * Eine leere Liste bedeutet: die Regel greift nie.
 */
class CustomKeywordRule extends AbstractRule {

	public const ID             = 'custom_keyword';
	public const DEFAULT_POINTS = 25;

	/**
	 * Keyword-Liste.
	 *
	 * @var array<int, string>
	 */
	protected array $keywords;

	/**
	 * @param array<int, string> $keywords Keywords des Betreibers.
	 * @param int                $points   Punkte.
	 */
	public function __construct( array $keywords, int $points = self::DEFAULT_POINTS ) {
		parent::__construct( $points );
		$this->keywords = $keywords;
	}

	public function id(): string {
		return self::ID;
	}

	public function stage(): int {
		return 2;
	}

	public function applies( Context $context ): bool {
		foreach ( $this->keywords as $keyword ) {
			if ( '' !== trim( (string) $keyword ) ) {
				return true;
			}
		}
		return false;
	}

	public function evaluate( Context $context ): RuleResult {
		$haystack = implode(
			"\n",
			array(
				$context->field( 'content' ),
				$context->field( 'author_name' ),
				$context->field( 'author_url' ),
			)
		);
		if ( '' === trim( $haystack ) ) {
			return $this->miss();
		}

		foreach ( $this->keywords as $keyword ) {
			$keyword = trim( (string) $keyword );
			if ( '' !== $keyword && false !== mb_stripos( $haystack, $keyword ) ) {
				return $this->hit();
			}
		}
		return $this->miss();
	}
}
