<?php
/**
 * Post and page editing controls.
 *
 * @package HaPantheon
 */

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

/**
 * Sanitize a YouTube video ID without changing its case.
 *
 * YouTube IDs are case-sensitive and may contain letters, numbers,
 * underscores and hyphens.
 *
 * @param mixed $value Raw video ID.
 * @return string
 */
function hapantheon_sanitize_youtube_id( $value ) {
	return (string) preg_replace( '/[^A-Za-z0-9_-]/', '', (string) $value );
}

/**
 * Register theme metadata so it can be edited through the REST-powered block editor.
 */
function hapantheon_register_post_meta() {
	$text_fields = array(
		'_hapantheon_featured_url',
		'_hapantheon_eyebrow',
		'_hapantheon_location',
		'_hapantheon_recipe_prep',
		'_hapantheon_recipe_wait',
		'_hapantheon_recipe_yield',
		'_hapantheon_recipe_difficulty',
		'_hapantheon_recipe_tests',
		'_hapantheon_recipe_video_id',
	);

	foreach ( $text_fields as $key ) {
		$sanitize_callback = '_hapantheon_recipe_video_id' === $key
			? 'hapantheon_sanitize_youtube_id'
			: 'sanitize_text_field';

		register_post_meta(
			'post',
			$key,
			array(
				'type'              => 'string',
				'single'            => true,
				'show_in_rest'      => true,
					'sanitize_callback' => $sanitize_callback,
				'auth_callback'     => function () {
					return current_user_can( 'edit_posts' );
				},
			)
		);
	}

	$number_fields = array(
		'_hapantheon_reading_time',
		'_hapantheon_archive_number',
	);
	foreach ( $number_fields as $key ) {
		register_post_meta(
			'post',
			$key,
			array(
				'type'              => 'integer',
				'single'            => true,
				'show_in_rest'      => true,
				'sanitize_callback' => 'absint',
				'auth_callback'     => function () {
					return current_user_can( 'edit_posts' );
				},
			)
		);
	}
}
add_action( 'init', 'hapantheon_register_post_meta' );

/**
 * Add the article-options meta box.
 */
function hapantheon_add_meta_boxes() {
	add_meta_box(
		'hapantheon-article-options',
		__( 'HaPantheon article options', 'hapantheon' ),
		'hapantheon_render_article_meta_box',
		'post',
		'normal',
		'default'
	);
}
add_action( 'add_meta_boxes', 'hapantheon_add_meta_boxes' );

/**
 * Render a text field in the article-options meta box.
 *
 * @param string $key         Meta key.
 * @param string $label       Field label.
 * @param string $description Help text.
 * @param string $type        Input type.
 */
function hapantheon_meta_field( $key, $label, $description = '', $type = 'text' ) {
	$value = get_post_meta( get_the_ID(), $key, true );
	?>
	<p class="hapantheon-meta-field">
		<label for="<?php echo esc_attr( $key ); ?>"><strong><?php echo esc_html( $label ); ?></strong></label><br>
		<input
			class="widefat"
			type="<?php echo esc_attr( $type ); ?>"
			id="<?php echo esc_attr( $key ); ?>"
			name="<?php echo esc_attr( $key ); ?>"
			value="<?php echo esc_attr( $value ); ?>"
			<?php echo 'number' === $type ? 'min="0" step="1"' : ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
		>
		<?php if ( $description ) : ?>
			<small style="display:block;margin-top:4px;color:#646970"><?php echo esc_html( $description ); ?></small>
		<?php endif; ?>
	</p>
	<?php
}

/**
 * Render the article-options fields.
 *
 * @param WP_Post $post Current post.
 */
function hapantheon_render_article_meta_box( $post ) {
	wp_nonce_field( 'hapantheon_save_article_meta', 'hapantheon_article_meta_nonce' );
	?>
	<style>
		#hapantheon-article-options .inside{display:grid;grid-template-columns:repeat(2,minmax(220px,1fr));gap:0 18px}
		#hapantheon-article-options .hapantheon-meta-intro{grid-column:1/-1}
		@media(max-width:782px){#hapantheon-article-options .inside{grid-template-columns:1fr}}
	</style>
	<p class="hapantheon-meta-intro">
		<?php esc_html_e( 'These fields control article labels, metadata and recipe facts. The article body itself remains fully editable in the WordPress block editor.', 'hapantheon' ); ?>
	</p>
	<?php
	hapantheon_meta_field( '_hapantheon_featured_url', __( 'Remote featured-image URL', 'hapantheon' ), __( 'Used only when no WordPress featured image is selected.', 'hapantheon' ), 'url' );
	hapantheon_meta_field( '_hapantheon_eyebrow', __( 'Eyebrow / archive label', 'hapantheon' ), __( 'Example: ALPHA · Recipes · Scroll no. 7', 'hapantheon' ) );
	hapantheon_meta_field( '_hapantheon_location', __( 'Location or secondary meta', 'hapantheon' ), __( 'Optional text shown beside the date and reading time.', 'hapantheon' ) );
	hapantheon_meta_field( '_hapantheon_reading_time', __( 'Reading time (minutes)', 'hapantheon' ), __( 'Leave empty or zero to calculate it automatically.', 'hapantheon' ), 'number' );
	hapantheon_meta_field( '_hapantheon_archive_number', __( 'Archive / scroll number', 'hapantheon' ), __( 'Optional internal display number.', 'hapantheon' ), 'number' );
	hapantheon_meta_field( '_hapantheon_recipe_prep', __( 'Recipe: preparation time', 'hapantheon' ), __( 'Example: 10 minutes', 'hapantheon' ) );
	hapantheon_meta_field( '_hapantheon_recipe_wait', __( 'Recipe: waiting time', 'hapantheon' ), __( 'Example: 16 hours', 'hapantheon' ) );
	hapantheon_meta_field( '_hapantheon_recipe_yield', __( 'Recipe: yield', 'hapantheon' ), __( 'Example: 4 glasses', 'hapantheon' ) );
	hapantheon_meta_field( '_hapantheon_recipe_difficulty', __( 'Recipe: difficulty', 'hapantheon' ), __( 'Example: Easy', 'hapantheon' ) );
	hapantheon_meta_field( '_hapantheon_recipe_tests', __( 'Recipe: tests / iterations', 'hapantheon' ), __( 'Example: Tested 23 times', 'hapantheon' ) );
	hapantheon_meta_field( '_hapantheon_recipe_video_id', __( 'Recipe: YouTube video ID', 'hapantheon' ), __( 'Only the video ID, not the full URL.', 'hapantheon' ) );
}

/**
 * Save the article-options fields.
 *
 * @param int $post_id Post ID.
 */
function hapantheon_save_article_meta( $post_id ) {
	if (
		! isset( $_POST['hapantheon_article_meta_nonce'] ) ||
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['hapantheon_article_meta_nonce'] ) ), 'hapantheon_save_article_meta' )
	) {
		return;
	}

	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}

	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		return;
	}

	$text_fields = array(
		'_hapantheon_featured_url'          => 'esc_url_raw',
		'_hapantheon_eyebrow'               => 'sanitize_text_field',
		'_hapantheon_location'              => 'sanitize_text_field',
		'_hapantheon_recipe_prep'            => 'sanitize_text_field',
		'_hapantheon_recipe_wait'            => 'sanitize_text_field',
		'_hapantheon_recipe_yield'           => 'sanitize_text_field',
		'_hapantheon_recipe_difficulty'      => 'sanitize_text_field',
		'_hapantheon_recipe_tests'           => 'sanitize_text_field',
		'_hapantheon_recipe_video_id'        => 'hapantheon_sanitize_youtube_id',
	);

	foreach ( $text_fields as $key => $callback ) {
		if ( ! array_key_exists( $key, $_POST ) ) {
			continue;
		}
		$value = call_user_func( $callback, wp_unslash( $_POST[ $key ] ) );
		if ( '' === $value ) {
			delete_post_meta( $post_id, $key );
		} else {
			update_post_meta( $post_id, $key, $value );
		}
	}

	foreach ( array( '_hapantheon_reading_time', '_hapantheon_archive_number' ) as $key ) {
		if ( ! array_key_exists( $key, $_POST ) ) {
			continue;
		}
		$value = absint( $_POST[ $key ] );
		if ( $value ) {
			update_post_meta( $post_id, $key, $value );
		} else {
			delete_post_meta( $post_id, $key );
		}
	}
}
add_action( 'save_post_post', 'hapantheon_save_article_meta' );
