<?php
/**
 * Register post meta for REST API access.
 *
 * This enables Claude Code and other automation tools to read/write
 * all SEO fields via the standard WordPress REST API.
 *
 * Example: PATCH /wp-json/wp/v2/pages/{id} { "meta": { "_dennis_seo_title": "..." } }
 *
 * @package Dennis_SEO
 * @license GPL-2.0-or-later
 */

defined( 'ABSPATH' ) || exit;

class Dennis_SEO_Rest_Meta {

	/**
	 * Meta keys with their sanitize callbacks — references DENNIS_SEO_META_KEYS from dennis-seo.php.
	 */

	public function __construct() {
		add_action( 'init', array( $this, 'register_meta' ) );
		add_action( 'rest_api_init', array( $this, 'register_settings_endpoint' ) );
	}

	public function register_meta(): void {
		$post_types = get_post_types( array( 'public' => true ) );

		foreach ( $post_types as $pt ) {
			foreach ( DENNIS_SEO_META_KEYS as $key => $sanitize_cb ) {
				register_post_meta( $pt, $key, array(
					'show_in_rest'      => true,
					'single'            => true,
					'type'              => 'string',
					'default'           => '',
					'sanitize_callback' => $sanitize_cb,
					'auth_callback'     => function () {
						return current_user_can( 'edit_posts' );
					},
				) );
			}
		}
	}

	/**
	 * REST endpoint for reading/writing global settings.
	 */
	public function register_settings_endpoint(): void {
		register_rest_route( 'dennis-seo/v1', '/settings', array(
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_settings' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_options' );
				},
			),
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'update_settings' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_options' );
				},
			),
		) );
	}

	public function get_settings(): \WP_REST_Response {
		return new \WP_REST_Response( Dennis_SEO_Settings::get_all(), 200 );
	}

	public function update_settings( \WP_REST_Request $request ): \WP_REST_Response {
		$data     = $request->get_json_params();
		$defaults = Dennis_SEO_Settings::get_all();

		// Whitelist: only allow known keys.
		$filtered = array_intersect_key( $data, $defaults );

		$merged = wp_parse_args( $filtered, $defaults );

		// Sanitize.
		foreach ( $merged as $key => $value ) {
			if ( is_bool( $value ) ) {
				$merged[ $key ] = (bool) $value;
			} elseif ( is_string( $value ) ) {
				$merged[ $key ] = sanitize_text_field( $value );
			}
		}

		update_option( Dennis_SEO_Settings::OPTION_KEY, $merged );

		// Bust all caches.
		delete_transient( 'dennis_seo_llms_txt' );
		delete_transient( 'dennis_seo_llms_full_txt' );
		delete_transient( 'dennis_seo_sitemap_post' );
		delete_transient( 'dennis_seo_sitemap_page' );

		return new \WP_REST_Response( $merged, 200 );
	}
}
