<?php
/**
 * Gutenberg block editor integration.
 *
 * @package AIAltTextGenerator
 * @since 1.5.0
 */

namespace AIAltTextGenerator;

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

/**
 * @since 1.5.0
 */
class BlockEditor {

	public function register(): void {
		add_action( 'enqueue_block_editor_assets', [ $this, 'enqueueAssets' ] );
		add_action( 'rest_api_init', [ $this, 'registerRestRoutes' ] );
	}

	public function enqueueAssets(): void {
		if ( ! Capabilities::canGenerate() ) {
			return;
		}

		$base = WP_POWERSUITE_PLUGIN_URL . 'modules/ai-alt-text-generator/assets/';
		wp_enqueue_script(
			'wpps-ai-alt-gutenberg',
			$base . 'ai-alt-text-gutenberg.js',
			[ 'wp-plugins', 'wp-edit-post', 'wp-element', 'wp-components', 'wp-data', 'wp-i18n', 'wp-block-editor' ],
			'1.5.0',
			true
		);

		wp_localize_script(
			'wpps-ai-alt-gutenberg',
			'wppsAiAltGutenberg',
			[
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( Module::nonceAction() ),
				'restUrl' => rest_url( 'wp-powersuite/v1/ai-alt-text/' ),
				'restNonce' => wp_create_nonce( 'wp_rest' ),
				'hasApiKey' => Settings::hasApiKey(),
				'strings' => [
					'panelTitle'  => __( 'AI Alt Text', 'wp-powersuite' ),
					'generate'    => __( 'Generate with AI', 'wp-powersuite' ),
					'local'       => __( 'Local suggestion', 'wp-powersuite' ),
					'saveBlock'   => __( 'Apply to block', 'wp-powersuite' ),
					'saveMedia'   => __( 'Save to media library', 'wp-powersuite' ),
					'decorative'  => __( 'Mark decorative', 'wp-powersuite' ),
					'noImage'     => __( 'Select an image block to generate alt text.', 'wp-powersuite' ),
					'noApiKey'    => __( 'Configure an API key in module settings.', 'wp-powersuite' ),
					'generating'  => __( 'Generating...', 'wp-powersuite' ),
					'saved'       => __( 'Saved.', 'wp-powersuite' ),
					'error'       => __( 'An error occurred.', 'wp-powersuite' ),
				],
			]
		);
	}

	public function registerRestRoutes(): void {
		register_rest_route(
			'wp-powersuite/v1',
			'/ai-alt-text/attachment/(?P<id>\d+)/status',
			[
				'methods'             => 'GET',
				'callback'            => [ $this, 'attachmentStatus' ],
				'permission_callback' => static function (): bool {
					return Capabilities::canGenerate();
				},
				'args'                => [
					'id' => [
						'type'              => 'integer',
						'required'          => true,
						'sanitize_callback' => 'absint',
					],
				],
			]
		);
	}

	public function attachmentStatus( \WP_REST_Request $request ): \WP_REST_Response {
		$id = (int) $request->get_param( 'id' );
		if ( ! current_user_can( 'edit_post', $id ) ) {
			return new \WP_REST_Response( [ 'message' => __( 'Permission denied.', 'wp-powersuite' ) ], 403 );
		}

		$alt        = (string) get_post_meta( $id, '_wp_attachment_image_alt', true );
		$suggestion = AttachmentMeta::getSuggestion( $id );
		$status     = AttachmentStatus::resolve( $id );

		return new \WP_REST_Response(
			[
				'attachment_id' => $id,
				'alt_text'      => $alt,
				'suggestion'    => $suggestion,
				'status'        => $status,
			]
		);
	}
}
