<?php
/**
 * Badges for the pages this plugin owns.
 *
 * @package WarrantyCart
 */

namespace WarrantyCart\Admin;

use WarrantyCart\Frontend\Shortcode;
use WP_Post;

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

/**
 * Labels the plugin's pages in Pages → All Pages.
 *
 * Without this, the page carrying the warranty selector is indistinguishable
 * from any other page in the list — so it gets renamed, trashed or duplicated
 * by somebody who had no way to know it was load-bearing. WooCommerce marks
 * its own pages the same way ("Shop Page", "Cart Page"), which is the
 * convention administrators already read.
 */
class PostStates {

	/**
	 * Constructor
	 */
	public function __construct() {
		\add_filter( 'display_post_states', array( $this, 'add_post_states' ), 10, 2 );
	}

	/**
	 * Append this plugin's badges to a page's states.
	 *
	 * @param array<string, string> $states Existing post states.
	 * @param WP_Post|null          $post   The post being listed.
	 *
	 * @return array<string, string>
	 */
	public function add_post_states( $states, $post ): array {
		if ( ! is_array( $states ) || ! $post instanceof WP_Post ) {
			return is_array( $states ) ? $states : array();
		}

		$page_id = (int) $post->ID;

		/*
		 * The stored option, not Shortcode::display_page_id().
		 *
		 * That helper returns 0 for a page that is not published, which is
		 * right for the frontend but wrong here: a draft or pending page is
		 * exactly the one an administrator needs to see marked, because it is
		 * selected in the settings and silently doing nothing.
		 */
		$selected = (int) \get_option( Shortcode::PAGE_OPTION, 0 );

		if ( $selected > 0 && $selected === $page_id ) {
			$states['warranty_cart_page'] = 'publish' === $post->post_status
				? \__( 'Warranty Page', 'warranty-cart' )
				: \__( 'Warranty Page (not published)', 'warranty-cart' );
		}

		$terms_page = (int) \get_option( 'warranty_cart_terms_page', 0 );

		if ( $terms_page > 0 && $terms_page === $page_id ) {
			$states['warranty_cart_terms_page'] = \__( 'Warranty Terms', 'warranty-cart' );
		}

		return $states;
	}
}
