<?php
	/**
	 * Plugin Name: Post Short Description
	 * Description: Adds Short Description field for posts and pages.
	 * Version: 1.0
	 */

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

	/**
	 * Register meta boxes.
	 */
	add_action(
		'add_meta_boxes',
		function () {

			$post_types = [ 'post', 'page' ];

			foreach ( $post_types as $post_type ) {

				add_meta_box(
					'post_short_description_box',
					'Short Description',
					'render_post_short_description_box',
					$post_type,
					'normal',
					'high'
				);

			}

		}
	);

	/**
	 * Render short description field.
	 *
	 * @param WP_Post $post Current post object.
	 *
	 * @return void
	 */
	function render_post_short_description_box( $post ) {

		wp_nonce_field(
			'save_post_short_description',
			'post_short_description_nonce'
		);

		$value = get_post_meta(
			$post->ID,
			'short_description',
			true
		);

		?>
		<textarea
			name="post_short_description"
			style="width:100%;min-height:100px;"
		><?php echo esc_textarea( $value ); ?></textarea>
		<p style="margin-top:8px;color:#666;">
			Used in cards, previews and snippets.
		</p>
		<?php
	}

	/**
	 * Save short description.
	 */
	add_action(
		'save_post',
		function ( $post_id ) {

			if ( ! isset( $_POST['post_short_description_nonce'] ) ) {
				return;
			}

			if (
				! wp_verify_nonce(
					$_POST['post_short_description_nonce'],
					'save_post_short_description'
				)
			) {
				return;
			}

			// Skip autosave requests.
			if (
				defined( 'DOING_AUTOSAVE' ) &&
				DOING_AUTOSAVE
			) {
				return;
			}

			// Verify user capabilities.
			if (
				! current_user_can(
					'edit_post',
					$post_id
				)
			) {
				return;
			}

			if ( isset( $_POST['post_short_description'] ) ) {

				update_post_meta(
					$post_id,
					'short_description',
					sanitize_textarea_field(
						$_POST['post_short_description']
					)
				);

			}

		}
	);

	/**
	 * Register meta field for REST API.
	 */
	add_action(
		'init',
		function () {

			$post_types = [ 'post', 'page' ];

			foreach ( $post_types as $post_type ) {

				register_post_meta(
					$post_type,
					'short_description',
					[
						'show_in_rest' => true,
						'single'       => true,
						'type'         => 'string',
					]
				);

			}

		}
	);