<?php
declare( strict_types=1 );

namespace FiboFilters\Config;

use FiboFilters\WooCommerce\Helper as WooCommerceHelper;

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

/**
 * Class IndexPusher
 */
class IndexPusher {
	const HOOK = 'fibofilters/indexer/index_pusher';

	/** @var WooCommerceHelper */
	private $wc_helper;

	public function __construct( WooCommerceHelper $wc_helper ) {
		$this->wc_helper = $wc_helper;
	}

	public function init(): void {
		add_action( 'upgrader_process_complete', [ $this, 'push_index_after_plugin_update' ], 10, 2 );
	}

	/**
	 * Schedule to index pusher
	 */
	public function schedule(): void {
		$queue = $this->wc_helper->get_queue();
		if ( empty( $queue ) ) {
			return;
		}

		// Check if there is task scheduled for this product.
		$is_scheduled = $queue->search(
			[
				'hook'   => self::HOOK,
				'status' => 'pending',
			]
		);

		if ( empty( $is_scheduled ) ) {
			/**
			 * Handler for this action is in the @see \FiboFilters\Config\Initializer::initialize method.
			 */
			$queue->add( self::HOOK );
		}
	}

	/**
	 * Pushes the index-building process further after updating the plugin
	 *
	 * @param \WP_Upgrader $upgrader_object Upgrader object.
	 * @param array        $options Upgrader options.
	 */
	public function push_index_after_plugin_update( $upgrader_object, $options ): void {
		$proper_action = ! empty( $options['action'] ) && in_array( $options['action'], [ 'update', 'install' ], true );
		$proper_type   = ! empty( $options['type'] ) && $options['type'] === 'plugin';
		$proper_plugin = false;
		$res           = $upgrader_object->result;
		$files         = ! empty( $res['source_files'] ) && is_array( $res['source_files'] ) ? $res['source_files'] : [];
		$dest          = ! empty( $res['destination_name'] ) && is_string( $res['destination_name'] ) ? $res['destination_name'] : '';

		if ( in_array( 'fibofilters.php', $files, true ) && strpos( $dest, 'fibofilters' ) !== false ) {
			$proper_plugin = true;
		}

		if ( $proper_action && $proper_type && $proper_plugin ) {
			/**
			 * To run an indexer after the plugin installation or updating we need call "admin_init" action.
			 *
			 * An "admin_init" action isn't called in the following cases:
			 *     1. Automatic updates
			 *     2. Updates by WP CLI
			 *     3. Updates by REST API
			 *     4. By WP Dashboard but without refreshing the page after updating
			 *
			 * Calling /wp-admin/admin-post.php fires do_action( 'admin_init' );. Login is not required.
			 */
			$code = wp_remote_retrieve_response_code( wp_remote_get( admin_url( 'admin-post.php' ) ) );
			if ( $code !== 200 ) {
				// Add a task via Action Scheduler on failure.
				$this->schedule();
			}
		}
	}
}
