<?php
/**
 * Testimonial post meta boxes.
 *
 * @package Rsmspark_Content_Widgets
 */

defined( 'ABSPATH' ) || exit;

/**
 * Rsmspark_Testimonials_Meta
 */
class Rsmspark_Testimonials_Meta {

	/**
	 * @return void
	 */
	public static function init() {
		add_action( 'add_meta_boxes', array( __CLASS__, 'register_meta_boxes' ) );
		add_action( 'save_post_' . Rsmspark_Testimonials_CPT::CPT, array( __CLASS__, 'save_post' ), 10, 2 );
	}

	/**
	 * @return void
	 */
	public static function register_meta_boxes() {
		add_meta_box(
			'rsmspark-testimonial-details',
			__( 'Profile details', 'rsm-content-widgets' ),
			array( __CLASS__, 'render_meta_box' ),
			Rsmspark_Testimonials_CPT::CPT,
			'normal',
			'high'
		);
	}

	/**
	 * @param WP_Post $post Post.
	 * @return void
	 */
	public static function render_meta_box( $post ) {
		wp_nonce_field( 'rsmspark_testimonial_save', 'rsmspark_testimonial_nonce' );
		$role = Rsmspark_Testimonials_CPT::get_role( $post->ID );
		?>
		<p>
			<label for="rsmspark_testimonial_role"><strong><?php esc_html_e( 'Role / title', 'rsm-content-widgets' ); ?></strong></label><br />
			<input type="text" class="widefat" id="rsmspark_testimonial_role" name="rsmspark_testimonial_role" value="<?php echo esc_attr( $role ); ?>" />
		</p>
		<p class="description">
			<?php esc_html_e( 'Use the title for the person’s name, the excerpt for a short quote, the content editor for the full bio (modal), and the featured image for their photo.', 'rsm-content-widgets' ); ?>
		</p>
		<?php
	}

	/**
	 * @param int     $post_id Post ID.
	 * @param WP_Post $post    Post.
	 * @return void
	 */
	public static function save_post( $post_id, $post ) {
		unset( $post );

		if ( ! isset( $_POST['rsmspark_testimonial_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( (string) $_POST['rsmspark_testimonial_nonce'] ) ), 'rsmspark_testimonial_save' ) ) {
			return;
		}

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

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

		if ( isset( $_POST['rsmspark_testimonial_role'] ) ) {
			Rsmspark_Testimonials_CPT::set_role(
				$post_id,
				sanitize_text_field( wp_unslash( (string) $_POST['rsmspark_testimonial_role'] ) )
			);
		}
	}
}
