<?php
/**
 * Registers per-post / per-page PDF meta fields.
 *
 * @package PDFDraft
 */

namespace PDFDraft\PostsToPdf;

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

/**
 * Exposes per-post PDF settings as REST-accessible post meta.
 *
 * _pdfdraft_pdf_template_id         — override template for this post (0 = use global)
 * _pdfdraft_pdf_button_visibility   — 'global' | 'show' | 'hide'
 */
class PostMetaFields {

	/**
	 * Register meta fields for posts and pages.
	 *
	 * @return void
	 */
	public function register(): void {
		foreach ( array( 'post', 'page' ) as $post_type ) {
			register_post_meta(
				$post_type,
				'_pdfdraft_pdf_template_id',
				array(
					'type'              => 'integer',
					'single'            => true,
					'default'           => 0,
					'show_in_rest'      => true,
					'auth_callback'     => array( $this, 'can_edit_post' ),
					'sanitize_callback' => 'absint',
				)
			);

			register_post_meta(
				$post_type,
				'_pdfdraft_pdf_button_visibility',
				array(
					'type'              => 'string',
					'single'            => true,
					'default'           => 'global',
					'show_in_rest'      => true,
					'auth_callback'     => array( $this, 'can_edit_post' ),
					'sanitize_callback' => array( $this, 'sanitize_visibility' ),
				)
			);
		}
	}

	/**
	 * Auth callback — requires edit_posts capability.
	 *
	 * @return bool
	 */
	public function can_edit_post(): bool {
		return current_user_can( 'edit_posts' );
	}

	/**
	 * Sanitize the button visibility value.
	 *
	 * @param mixed $value Raw input.
	 * @return string
	 */
	public function sanitize_visibility( $value ): string {
		$allowed = array( 'global', 'show', 'hide' );
		return in_array( $value, $allowed, true ) ? $value : 'global';
	}
}
