<?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;
		}

		$module_file = dirname( __DIR__ ) . '/module.php';
		$base        = function_exists( 'wp_powersuite_module_asset_url' )
			? rtrim( wp_powersuite_module_asset_url( $module_file, 'assets' ), '/' ) . '/'
			: plugins_url( 'assets/', $module_file );
		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', 'wppowersuite-lite' ),
					'generate'    => __( 'Generate with AI', 'wppowersuite-lite' ),
					'local'       => __( 'Local suggestion', 'wppowersuite-lite' ),
					'saveBlock'   => __( 'Apply to block', 'wppowersuite-lite' ),
					'saveMedia'   => __( 'Save to media library', 'wppowersuite-lite' ),
					'decorative'  => __( 'Mark decorative', 'wppowersuite-lite' ),
					'noImage'     => __( 'Select an image block to generate alt text.', 'wppowersuite-lite' ),
					'noApiKey'    => __( 'Configure an API key in module settings.', 'wppowersuite-lite' ),
					'generating'  => __( 'Generating...', 'wppowersuite-lite' ),
					'saved'       => __( 'Saved.', 'wppowersuite-lite' ),
					'error'       => __( 'An error occurred.', 'wppowersuite-lite' ),
				],
			]
		);
	}

	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.', 'wppowersuite-lite' ) ], 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,
			]
		);
	}
}
