<?php
/**
 * Create Pages Admin-Post Action Handler
 *
 * @package AmbassadorHub\Admin\Setup
 */

namespace AmbassadorHub\Admin\Setup;

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

use function add_action;
use function add_query_arg;
use function admin_url;
use function array_filter;
use function check_admin_referer;
use function count;
use function current_user_can;
use function esc_html__;
use function wp_die;
use function wp_safe_redirect;

/**
 * Handles the admin-post action that triggers page creation.
 *
 * Wired to `admin_post_ambh_create_pages`. Verifies the nonce and capability,
 * delegates to PageInstaller::install(), then redirects back to the Tools tab
 * with a result summary in the query string.
 */
final class CreatePagesAction {

	/**
	 * Register the admin-post handler.
	 *
	 * Call from AdminModule::init().
	 *
	 * @return void
	 */
	public static function init(): void {
		add_action( 'admin_post_ambh_create_pages', array( self::class, 'handle' ) );
	}

	/**
	 * Process the page-creation request.
	 *
	 * @return void
	 */
	public static function handle(): void {
		check_admin_referer( 'ambh_create_pages', 'ambh_create_pages_nonce' );

		if ( ! current_user_can( 'ambh_manage_hub' ) ) {
			wp_die( esc_html__( 'You do not have permission to perform this action.', 'ambassadorhub' ) );
		}

		$results = PageInstaller::install();

		$created = count( array_filter( $results, static fn( array $r ): bool => 'created' === $r['status'] ) );
		$skipped = count( array_filter( $results, static fn( array $r ): bool => 'skipped' === $r['status'] ) );
		$synced  = count( array_filter( $results, static fn( array $r ): bool => 'synced' === $r['status'] ) );
		$errors  = count( array_filter( $results, static fn( array $r ): bool => 'error' === $r['status'] ) );

		wp_safe_redirect(
			add_query_arg(
				array(
					'page'               => 'ambassadorhub-settings',
					'tab'                => 'tools',
					'ambh_pages_created' => $created,
					'ambh_pages_skipped' => $skipped,
					'ambh_pages_synced'  => $synced,
					'ambh_pages_errors'  => $errors,
				),
				admin_url( 'admin.php' )
			)
		);
		exit;
	}
}
