<?php
/**
 * Testimonials admin screens and moderation.
 *
 * @package Rsmspark_Content_Widgets
 */

defined( 'ABSPATH' ) || exit;

/**
 * Rsmspark_Testimonials_Admin
 */
class Rsmspark_Testimonials_Admin {

	const MENU_SLUG = 'edit.php?post_type=rsmspark_testimonial';

	/**
	 * @return void
	 */
	public static function init() {
		add_action( 'admin_menu', array( __CLASS__, 'register_menu' ), 20 );
		add_action( 'admin_menu', array( __CLASS__, 'append_pending_badge' ), 999 );
		add_filter( 'parent_file', array( __CLASS__, 'filter_parent_file' ) );
		add_filter( 'submenu_file', array( __CLASS__, 'filter_submenu_file' ) );
		add_filter( 'manage_' . Rsmspark_Testimonials_CPT::CPT . '_posts_columns', array( __CLASS__, 'list_columns' ) );
		add_action( 'manage_' . Rsmspark_Testimonials_CPT::CPT . '_posts_custom_column', array( __CLASS__, 'list_column_content' ), 10, 2 );
		add_filter( 'post_row_actions', array( __CLASS__, 'row_actions' ), 10, 2 );
		add_action( 'admin_post_rsmspark_testimonial_moderate', array( __CLASS__, 'handle_moderate' ) );
		add_action( 'admin_notices', array( __CLASS__, 'moderation_notice' ) );
	}

	/**
	 * @return void
	 */
	public static function register_menu() {
		if ( ! current_user_can( 'edit_posts' ) ) {
			return;
		}

		$parent = Rsmspark_Content_Widgets_Admin::PAGE_SLUG;
		$title  = __( 'Testimonials', 'rsm-content-widgets' );

		if ( class_exists( 'Rsmspark_Suite', false ) ) {
			Rsmspark_Suite::register_parent();
			$parent = Rsmspark_Suite::parent_slug();
			$title  = '— ' . $title;
		}

		add_submenu_page(
			$parent,
			__( 'Testimonials', 'rsm-content-widgets' ),
			$title,
			'edit_posts',
			self::MENU_SLUG
		);
	}

	/**
	 * @return void
	 */
	public static function append_pending_badge() {
		// Visitor submissions are Pro-only; free build has no pending-form queue.
		if ( ! class_exists( 'Rsmspark_Testimonials_Library', false ) || ! method_exists( 'Rsmspark_Testimonials_Library', 'pending_count' ) ) {
			return;
		}

		$pending = Rsmspark_Testimonials_Library::pending_count();
		if ( $pending <= 0 ) {
			return;
		}

		global $submenu;
		if ( ! is_array( $submenu ) ) {
			return;
		}

		$badge = sprintf(
			' <span class="awaiting-mod count-%1$d"><span class="pending-count">%1$d</span></span>',
			$pending
		);

		foreach ( $submenu as $parent => $items ) {
			if ( ! is_array( $items ) ) {
				continue;
			}
			foreach ( $items as $index => $item ) {
				if ( ! is_array( $item ) || ( $item[2] ?? '' ) !== self::MENU_SLUG ) {
					continue;
				}
				$submenu[ $parent ][ $index ][0] .= $badge;
			}
		}
	}

	/**
	 * @param string $parent_file Parent file.
	 * @return string
	 */
	public static function filter_parent_file( $parent_file ) {
		global $typenow;

		if ( Rsmspark_Testimonials_CPT::CPT === $typenow ) {
			return class_exists( 'Rsmspark_Suite', false ) ? Rsmspark_Suite::parent_slug() : Rsmspark_Content_Widgets_Admin::PAGE_SLUG;
		}

		return $parent_file;
	}

	/**
	 * @param string $submenu_file Submenu file.
	 * @return string
	 */
	public static function filter_submenu_file( $submenu_file ) {
		global $typenow;

		if ( Rsmspark_Testimonials_CPT::CPT === $typenow ) {
			return self::MENU_SLUG;
		}

		return $submenu_file;
	}

	/**
	 * @param array<string, string> $columns Columns.
	 * @return array<string, string>
	 */
	public static function list_columns( $columns ) {
		$new = array();
		foreach ( $columns as $key => $label ) {
			$new[ $key ] = $label;
			if ( 'title' === $key ) {
				$new['rsmspark_role']  = __( 'Role', 'rsm-content-widgets' );
				$new['rsmspark_quote'] = __( 'Quote', 'rsm-content-widgets' );
			}
		}
		return $new;
	}

	/**
	 * @param string $column  Column key.
	 * @param int    $post_id Post ID.
	 * @return void
	 */
	public static function list_column_content( $column, $post_id ) {
		if ( 'rsmspark_role' === $column ) {
			echo esc_html( Rsmspark_Testimonials_CPT::get_role( $post_id ) );
			return;
		}

		if ( 'rsmspark_quote' === $column ) {
			echo esc_html( wp_trim_words( get_the_excerpt( $post_id ), 12, '…' ) );
		}
	}

	/**
	 * @param array<string, string> $actions Row actions.
	 * @param WP_Post               $post    Post.
	 * @return array<string, string>
	 */
	public static function row_actions( $actions, $post ) {
		if ( ! $post instanceof WP_Post || Rsmspark_Testimonials_CPT::CPT !== $post->post_type ) {
			return $actions;
		}

		if ( 'pending' !== $post->post_status || ! current_user_can( 'publish_posts' ) ) {
			return $actions;
		}

		$approve_url = wp_nonce_url(
			add_query_arg(
				array(
					'action'   => 'rsmspark_testimonial_moderate',
					'post_id'  => $post->ID,
					'decision' => 'approve',
				),
				admin_url( 'admin-post.php' )
			),
			'rsmspark_testimonial_moderate_' . $post->ID
		);

		$reject_url = wp_nonce_url(
			add_query_arg(
				array(
					'action'   => 'rsmspark_testimonial_moderate',
					'post_id'  => $post->ID,
					'decision' => 'reject',
				),
				admin_url( 'admin-post.php' )
			),
			'rsmspark_testimonial_moderate_' . $post->ID
		);

		$actions['rsmspark_approve'] = sprintf(
			'<a href="%s">%s</a>',
			esc_url( $approve_url ),
			esc_html__( 'Approve', 'rsm-content-widgets' )
		);
		$actions['rsmspark_reject'] = sprintf(
			'<a href="%s" style="color:#b32d2e;">%s</a>',
			esc_url( $reject_url ),
			esc_html__( 'Reject', 'rsm-content-widgets' )
		);

		return $actions;
	}

	/**
	 * @return void
	 */
	public static function handle_moderate() {
		$post_id  = isset( $_GET['post_id'] ) ? absint( $_GET['post_id'] ) : 0;
		$decision = isset( $_GET['decision'] ) ? sanitize_key( wp_unslash( (string) $_GET['decision'] ) ) : '';

		if ( $post_id <= 0 || ! Rsmspark_Testimonials_CPT::is_testimonial_post( $post_id ) ) {
			wp_die( esc_html__( 'Invalid testimonial.', 'rsm-content-widgets' ) );
		}

		check_admin_referer( 'rsmspark_testimonial_moderate_' . $post_id );

		if ( ! current_user_can( 'publish_posts' ) ) {
			wp_die( esc_html__( 'You cannot moderate testimonials.', 'rsm-content-widgets' ) );
		}

		if ( 'approve' === $decision ) {
			wp_update_post(
				array(
					'ID'          => $post_id,
					'post_status' => 'publish',
				)
			);
			$notice = 'approved';
		} elseif ( 'reject' === $decision ) {
			wp_trash_post( $post_id );
			$notice = 'rejected';
		} else {
			wp_die( esc_html__( 'Invalid action.', 'rsm-content-widgets' ) );
		}

		wp_safe_redirect(
			add_query_arg(
				array(
					'post_type'                => Rsmspark_Testimonials_CPT::CPT,
					'rsmspark_testimonial_msg' => $notice,
				),
				admin_url( 'edit.php' )
			)
		);
		exit;
	}

	/**
	 * @return void
	 */
	public static function moderation_notice() {
		// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only admin notice flag; no state change.
		if ( ! isset( $_GET['rsmspark_testimonial_msg'] ) || ! isset( $_GET['post_type'] ) ) {
			return;
		}

		if ( Rsmspark_Testimonials_CPT::CPT !== sanitize_key( wp_unslash( (string) $_GET['post_type'] ) ) ) {
			return;
		}

		$msg = sanitize_key( wp_unslash( (string) $_GET['rsmspark_testimonial_msg'] ) );
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
		if ( 'approved' === $msg ) {
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Testimonial approved and published.', 'rsm-content-widgets' ) . '</p></div>';
		} elseif ( 'rejected' === $msg ) {
			echo '<div class="notice notice-info is-dismissible"><p>' . esc_html__( 'Testimonial rejected and moved to trash.', 'rsm-content-widgets' ) . '</p></div>';
		}
	}
}
