<?php

	/**
	 * Plugin Name: Post Featured Popular
	 * Description: Adds single Popular Post toggle for posts.
	 * Version: 1.0
	 */

	if ( ! defined( 'ABSPATH' ) ) {

		exit;

	}

	/**
	 * Add meta box
	 */

	add_action( 'add_meta_boxes', function () {

		add_meta_box(
			'post_popular_box',
			'Popular Post',
			'render_post_popular_box',
			'post',
			'normal',
			'high'
		);

	} );

	/**
	 * Meta box HTML
	 */

	function render_post_popular_box( $post ) {

		wp_nonce_field(
			'save_post_popular',
			'post_popular_nonce'
		);

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

		?>
		<label
			for="post_is_popular"
			style="
			display:flex;
			align-items:center;
			gap:8px;
			font-weight:500;
		"
		>
			<input
				type="checkbox"
				style="margin: 0"
				id="post_is_popular"
				name="post_is_popular"
				value="1"
				<?php checked( $is_popular, '1' ); ?>
			>
			<span>
			Mark as popular post
		</span>
		</label>
		<p style="margin-top:10px;color:#666;">
			Only one post can be marked as popular.
		</p>
		<?php

	}

	/**
	 * Save meta
	 */

	add_action( 'save_post_post', function ( $post_id ) {

		/**
		 * Nonce
		 */

		if ( ! isset( $_POST['post_popular_nonce'] ) ) {

			return;

		}

		if (
			! wp_verify_nonce(
				$_POST['post_popular_nonce'],
				'save_post_popular'
			)
		) {

			return;

		}

		/**
		 * Autosave
		 */

		if (
			defined( 'DOING_AUTOSAVE' ) &&
			DOING_AUTOSAVE
		) {

			return;

		}

		/**
		 * Permissions
		 */

		if (
			! current_user_can(
				'edit_post',
				$post_id
			)
		) {

			return;

		}

		/**
		 * Current value
		 */

		$is_popular = isset( $_POST['post_is_popular'] )
			? '1'
			: '0';

		/**
		 * If current post is popular
		 * reset all other posts
		 */

		if ( '1' === $is_popular ) {

			$popular_posts = get_posts(
				[
					'post_type'      => 'post',
					'post_status'    => 'any',
					'posts_per_page' => - 1,
					'post__not_in'   => [ $post_id ],
					'meta_key'       => 'is_popular',
					'meta_value'     => '1',
					'fields'         => 'ids',
				]
			);

			if ( ! empty( $popular_posts ) ) {

				foreach ( $popular_posts as $popular_post_id ) {

					update_post_meta(
						$popular_post_id,
						'is_popular',
						'0'
					);

				}

			}

		}

		/**
		 * Save current post
		 */

		update_post_meta(
			$post_id,
			'is_popular',
			$is_popular
		);

	} );

	/**
	 * Register REST API meta
	 */

	add_action( 'init', function () {

		register_post_meta(
			'post',
			'is_popular',
			[
				'show_in_rest' => true,
				'single'       => true,
				'type'         => 'string',
				'default'      => '0',
			]
		);

	} );