<?php
/**
 * WP Async Request
 *
 * Based on WP Background Processing by Delicious Brains: https://github.com/deliciousbrains/wp-background-processing/blob/master/classes/wp-async-request.php
 */

declare( strict_types=1 );

namespace FiboFilters\Indexer\BackgroundProcessing;

use FiboFilters\Indexer\Logger;

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

/**
 * Abstract AsyncRequest class.
 */
abstract class AsyncRequest {

	/**
	 * Prefix
	 *
	 * (default value: 'wp')
	 *
	 * @var string
	 * @access protected
	 */
	protected $prefix = 'wp';

	/**
	 * Action
	 *
	 * (default value: 'async_request')
	 *
	 * @var string
	 * @access protected
	 */
	protected $action = 'async_request';

	/**
	 * Identifier
	 *
	 * @var mixed
	 * @access protected
	 */
	protected $identifier;

	/**
	 * Friendly name
	 *
	 * @var string
	 * @access protected
	 */
	protected $name = '';

	/**
	 * Data
	 *
	 * (default value: [])
	 *
	 * @var array
	 * @access protected
	 */
	protected $data = [];

	/** @var Logger */
	protected $logger;

	/**
	 * Initiate new async request
	 *
	 * @param Logger $logger Logger.
	 */
	public function __construct( Logger $logger ) {
		$this->identifier = $this->prefix . '_' . $this->action;

		$this->logger = $logger;
	}

	public function init_handler(): void {
		add_action( 'wp_ajax_' . $this->identifier, [ $this, 'maybe_handle' ] );
		add_action( 'wp_ajax_nopriv_' . $this->identifier, [ $this, 'maybe_handle' ] );
	}

	/**
	 * Set data used during the request
	 *
	 * @param array $data Data.
	 *
	 * @return $this
	 */
	public function data( array $data ) {
		$this->data = $data;

		return $this;
	}

	/**
	 * Dispatch the async request
	 *
	 * @return array|\WP_Error
	 */
	public function dispatch() {
		$this->logger->log( $this->name . ' Dispatching new process via HTTP POST', 'debug', 'file', 'bg-process' );

		$url  = add_query_arg( $this->get_query_args(), $this->get_query_url() );
		$args = $this->get_post_args();

		return wp_remote_post( esc_url_raw( $url ), $args );
	}

	/**
	 * Get query args
	 */
	protected function get_query_args(): array {
		if ( property_exists( $this, 'query_args' ) ) {
			return $this->query_args;
		}

		$args = [
			'action' => $this->identifier,
			'nonce'  => wp_create_nonce( $this->identifier ),
		];

		/**
		 * Filters the post arguments used during an async request.
		 *
		 * @param array $url
		 */
		return apply_filters( "fibofilters/{$this->identifier}/query_args", $args );
	}

	/**
	 * Get query URL
	 */
	protected function get_query_url(): string {
		if ( property_exists( $this, 'query_url' ) ) {
			return $this->query_url;
		}

		$url = admin_url( 'admin-ajax.php' );

		/**
		 * Filters the post arguments used during an async request.
		 *
		 * @param string $url
		 */
		return apply_filters( "fibofilters/{$this->identifier}/query_url", $url );
	}

	/**
	 * Get post args
	 */
	protected function get_post_args(): array {
		if ( property_exists( $this, 'post_args' ) ) {
			return $this->post_args;
		}

		$args = [
			'timeout'   => 0.01,
			'blocking'  => false,
			'body'      => $this->data,
			'cookies'   => $_COOKIE,
			'sslverify' => apply_filters( 'https_local_ssl_verify', false ), // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
		];

		/**
		 * Filters the post arguments used during an async request.
		 *
		 * @param array $args
		 */
		return apply_filters( "fibofilters/{$this->identifier}/post_args", $args );
	}

	/**
	 * Maybe handle
	 *
	 * Check for correct nonce and pass to handler.
	 */
	public function maybe_handle(): void {
		// Don't lock up other requests while processing.
		session_write_close();

		check_ajax_referer( $this->identifier, 'nonce' );

		$raw_post_data = @file_get_contents( 'php://input' );
		if ( $raw_post_data !== false ) {
			parse_str( $raw_post_data, $params );
			$this->data = $params;
		}

		$this->handle();

		wp_die();
	}

	/**
	 * Handle
	 *
	 * Override this method to perform any actions required
	 * during the async request.
	 */
	abstract protected function handle(): void;
}
