<?php

namespace MDCE;

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

class SearchExclusion {

	private const CONFIG_META = '_mdce_exclude_search_on_expiry';
	private const ACTIVE_META = '_mdce_exclude_search_active';

	public function register(): void {
		add_action( 'mdce_meta_box_fields', [ $this, 'render_meta_box_field' ], 21, 2 );
		add_action( 'mdce_meta_box_save',   [ $this, 'save' ] );
		add_action( 'mdce_post_expired',    [ $this, 'handle_expired' ], 10, 2 );
		add_action( 'pre_get_posts',       [ $this, 'filter_search_query' ] );
		add_action( 'admin_init',          [ $this, 'handle_deactivate' ] );
	}

	public function render_meta_box_field( \WP_Post $post, string $current_action ): void {
		if ( get_post_meta( $post->ID, self::ACTIVE_META, true ) ) {
			$deactivate_url = wp_nonce_url(
				admin_url( 'post.php?post=' . $post->ID . '&action=edit&spe_deactivate=search' ),
				'spe_deactivate_search_' . $post->ID
			);
			?>
			<div class="spe-field-row">
				<div class="notice notice-info inline" style="margin:0; padding:6px 12px;">
					<p style="margin:0; font-size:12px;">
						<strong><?php esc_html_e( 'Excluded from site search', 'monkeydesign-content-expiry' ); ?></strong>
						— <a href="<?php echo esc_url( $deactivate_url ); ?>"><?php esc_html_e( 'Deactivate', 'monkeydesign-content-expiry' ); ?></a>
					</p>
				</div>
			</div>
			<?php
			return;
		}

		$checked = (bool) get_post_meta( $post->ID, self::CONFIG_META, true );
		?>
		<div class="spe-field-row">
			<label class="spe-check-item" style="font-size:12px; color:#50575e;">
				<input type="checkbox" name="spe_exclude_search" value="1" <?php checked( $checked ); ?>>
				<?php esc_html_e( 'Exclude from site search when expired', 'monkeydesign-content-expiry' ); ?>
			</label>
		</div>
		<?php
	}

	public function save( int $post_id ): void {
		if ( ! isset( $_POST['spe_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['spe_nonce'] ) ), 'spe_save_expiration' ) ) {
			return;
		}
		if ( isset( $_POST['spe_exclude_search'] ) ) {
			update_post_meta( $post_id, self::CONFIG_META, '1' );
			delete_post_meta( $post_id, self::ACTIVE_META );
		} else {
			delete_post_meta( $post_id, self::CONFIG_META );
			delete_post_meta( $post_id, self::ACTIVE_META );
		}
	}

	public function handle_expired( int $post_id, string $action ): void {
		if ( get_post_meta( $post_id, self::CONFIG_META, true ) ) {
			update_post_meta( $post_id, self::ACTIVE_META, '1' );
		}
	}

	public function filter_search_query( \WP_Query $query ): void {
		if ( is_admin() || ! $query->is_search() || ! $query->is_main_query() ) {
			return;
		}

		$existing = (array) $query->get( 'meta_query' );
		$existing[] = [
			'relation' => 'OR',
			[ 'key' => self::ACTIVE_META, 'compare' => 'NOT EXISTS' ],
			[ 'key' => self::ACTIVE_META, 'value' => '1', 'compare' => '!=' ],
		];
		$query->set( 'meta_query', $existing );
	}

	public function handle_deactivate(): void {
		if ( ! isset( $_GET['spe_deactivate'], $_GET['post'] ) || 'search' !== $_GET['spe_deactivate'] ) {
			return;
		}

		$post_id = (int) $_GET['post'];
		check_admin_referer( 'spe_deactivate_search_' . $post_id );

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			wp_die( esc_html__( 'You do not have permission to do this.', 'monkeydesign-content-expiry' ) );
		}

		delete_post_meta( $post_id, self::ACTIVE_META );

		wp_safe_redirect( admin_url( 'post.php?post=' . $post_id . '&action=edit' ) );
		exit;
	}
}
