<?php
/**
 * REST: GET /wp-json/sfrec/v1/status — the monitoring state and open findings,
 * for anyone who would rather read them from a script or a dashboard than from
 * wp-admin. Part of the free plugin, like the WP-CLI commands it mirrors.
 *
 * Reading requires `manage_options` (cookie auth or an application password),
 * exactly like the admin screens that show the same data.
 *
 * @package SEO_Flight_Recorder
 */

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

/**
 * Class SFRec_Rest
 */
class SFRec_Rest {

	/**
	 * Wire hooks.
	 */
	public static function init() {
		add_action( 'rest_api_init', array( __CLASS__, 'register_routes' ) );
	}

	/**
	 * Register the route.
	 */
	public static function register_routes() {
		register_rest_route(
			'sfrec/v1',
			'/status',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'permission_callback' => array( __CLASS__, 'can_read' ),
				'callback'            => array( __CLASS__, 'status' ),
			)
		);
	}

	/**
	 * Permission check.
	 *
	 * @return bool
	 */
	public static function can_read() {
		return current_user_can( 'manage_options' );
	}

	/**
	 * The status payload.
	 *
	 * @return WP_REST_Response
	 */
	public static function status() {
		global $wpdb;

		$state = get_option( 'sfrec_state', array() );
		$rows  = $wpdb->get_results( "SELECT id, page_id, field, before_val, after_val, severity, classification, status, detected_at FROM {$wpdb->prefix}sfrec_changes WHERE status IN ('new','seen') ORDER BY id DESC LIMIT 100", ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- own table.

		return rest_ensure_response(
			array(
				'site'            => wp_parse_url( home_url( '/' ), PHP_URL_HOST ),
				'loopback_ok'     => isset( $state['loopback_ok'] ) ? (bool) $state['loopback_ok'] : null,
				'last_check'      => isset( $state['last_check'] ) ? (int) $state['last_check'] : 0,
				'check_frequency' => SFRec_Scanner::frequency(),
				'monitored_pages' => count( SFRec_Scanner::pages() ),
				'sitemap_url'     => isset( $state['sitemap_url'] ) ? $state['sitemap_url'] : '',
				'sitemap_count'   => isset( $state['sitemap_count'] ) ? (int) $state['sitemap_count'] : 0,
				'open_findings'   => $rows,
			)
		);
	}
}
