<?php
/**
 * Spam Settings REST API Controller.
 *
 * @package Ugcify\Admin\API
 */

namespace Ugcify\Admin\API;

use WP_REST_Controller;
use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class SpamSettingsAPI
 */
class SpamSettingsAPI extends WP_REST_Controller {

	/**
	 * Namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'ugcify/v1';

	/**
	 * Rest base.
	 *
	 * @var string
	 */
	protected $rest_base = 'settings/spam';

	/**
	 * Option name for spam settings.
	 *
	 * @var string
	 */
	private $option_name = 'ugcify_spam_settings';

	/**
	 * Register routes.
	 */
	public function register_routes() {
		// Get spam settings.
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base,
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_settings' ),
					'permission_callback' => array( $this, 'check_permission' ),
				),
				array(
					'methods'             => WP_REST_Server::EDITABLE,
					'callback'            => array( $this, 'update_settings' ),
					'permission_callback' => array( $this, 'check_permission' ),
				),
			)
		);
	}

	/**
	 * Check permission — requires manage_options.
	 *
	 * @return bool|WP_Error
	 */
	public function check_permission() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return new WP_Error(
				'rest_forbidden',
				__( 'Sorry, you are not allowed to access this resource.', 'ugcify' ),
				array( 'status' => 403 )
			);
		}
		return true;
	}

	/**
	 * Get spam settings.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response
	 */
	public function get_settings( $request ) {
		$settings = $this->get_spam_settings();

		return rest_ensure_response(
			array(
				'success' => true,
				'data'    => $settings,
			)
		);
	}

	/**
	 * Update spam settings.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response|WP_Error
	 */
	public function update_settings( $request ) {
		$params = $request->get_json_params();

		if ( empty( $params ) ) {
			return new WP_Error(
				'invalid_data',
				__( 'Invalid data.', 'ugcify' ),
				array( 'status' => 400 )
			);
		}

		// Sanitize and validate settings.
		$settings = array(
			'enabled'    => isset( $params['enabled'] ) ? (bool) $params['enabled'] : false,
			'spam_words' => isset( $params['spam_words'] ) ? sanitize_textarea_field( $params['spam_words'] ) : '',
		);

		// Update settings.
		$result = update_option( $this->option_name, $settings, true );

		if ( false === $result && get_option( $this->option_name ) !== $settings ) {
			return new WP_Error(
				'update_failed',
				__( 'Failed to update spam settings.', 'ugcify' ),
				array( 'status' => 500 )
			);
		}

		return rest_ensure_response(
			array(
				'success' => true,
				'message' => __( 'Spam settings updated successfully.', 'ugcify' ),
				'data'    => $settings,
			)
		);
	}

	/**
	 * Get spam settings from database.
	 *
	 * @return array
	 */
	private function get_spam_settings() {
		$defaults = array(
			'enabled'    => false,
			'spam_words' => '',
		);

		$settings = get_option( $this->option_name, $defaults );

		// Ensure all keys exist.
		return wp_parse_args( $settings, $defaults );
	}

	/**
	 * Check if content contains spam words.
	 *
	 * @param string $content Content to check.
	 * @return bool True if spam detected.
	 */
	public static function is_spam( $content ) {
		$option_name = 'ugcify_spam_settings';
		$settings    = get_option( $option_name, array() );

		// If spam detection is disabled.
		if ( empty( $settings['enabled'] ) ) {
			return false;
		}

		// If no spam words configured.
		if ( empty( $settings['spam_words'] ) ) {
			return false;
		}

		// Parse spam words (comma-separated).
		$spam_words = array_map( 'trim', explode( ',', $settings['spam_words'] ) );
		$spam_words = array_filter( $spam_words ); // Remove empty entries.

		if ( empty( $spam_words ) ) {
			return false;
		}

		// Convert content to lowercase for case-insensitive matching.
		$content_lower = strtolower( $content );

		// Check if any spam word exists in content.
		foreach ( $spam_words as $word ) {
			$word_lower = strtolower( $word );
			if ( false !== strpos( $content_lower, $word_lower ) ) {
				return true;
			}
		}

		return false;
	}
}
