<?php
/**
 * Rescan automatique d'un plugin après mise à jour.
 *
 * @package PCC
 * @license GPL-2.0-or-later
 */

defined( 'ABSPATH' ) || exit;

class PCC_Auto_Rescan {

	/** @var PCC_Plugin */
	private $plugin;

	public function __construct( PCC_Plugin $plugin ) {
		$this->plugin = $plugin;
		add_action( 'upgrader_process_complete', array( $this, 'on_upgrade_complete' ), 10, 2 );
	}

	/**
	 * @param WP_Upgrader $upgrader
	 * @param array       $options
	 */
	public function on_upgrade_complete( $upgrader, $options ) {
		unset( $upgrader );

		if ( empty( $this->plugin->settings->get( 'auto_rescan_update' ) ) ) {
			return;
		}

		if ( ! $this->plugin->has_feature( 'scan_all_plugins' ) ) {
			return;
		}

		if ( ( $options['type'] ?? '' ) !== 'plugin' || ( $options['action'] ?? '' ) !== 'update' ) {
			return;
		}

		$plugins = $options['plugins'] ?? array();
		if ( empty( $plugins ) || ! is_array( $plugins ) ) {
			return;
		}

		$slug = dirname( $plugins[0] );
		if ( '.' === $slug ) {
			$slug = basename( $plugins[0], '.php' );
		}

		$config = array_merge(
			$this->plugin->settings->all(),
			array(
				'selected_plugins' => array( $slug ),
				'selected_themes'  => array(),
			)
		);

		$this->plugin->scanner->start_scan( $config, true );

		$guard = 0;
		do {
			$result = $this->plugin->scanner->process_batch();
			$guard++;
		} while ( empty( $result['done'] ) && $guard < 5000 );

		set_transient(
			'pcc_auto_rescan_notice',
			array(
				'slug'    => $slug,
				'verdict' => $this->plugin->settings->get_last_scan()['verdict'] ?? 'unknown',
			),
			DAY_IN_SECONDS
		);
	}
}
