<?php

namespace WC_Affiliate\API;

defined( 'ABSPATH' ) || exit;

use WC_Affiliate\Traits\Auth;
use WC_Affiliate\Traits\Rest;
use WC_Affiliate\Traits\Validation;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;

/**
 * REST API Controller for Notice Management.
 *
 * Handles REST API requests related to dismissing admin notices.
 *
 * @since 1.0.0
 */
class Notices {

	use Auth;

	use Rest;
	use Validation;

	/**
	 * Dismiss notice.
	 *
	 * @since 1.0.0
	 *
	 * @param WP_REST_Request $request The REST request object containing notice type.
	 *
	 * @return WP_REST_Response|WP_Error The response with dismissal result.
	 */
	public function dismiss_notice( WP_REST_Request $request ) {
		$notice_type = sanitize_text_field( $request->get_param( 'notice_type' ) );

		delete_transient( $notice_type );

		/**
		 * Fires after a notice is dismissed.
		 *
		 * @param string $notice_type The type of notice being dismissed.
		 *
		 * @since 1.0.0
		 */
		do_action( 'wc_affiliate_notice_dismissed', $notice_type );

		$url = wc_affiliate_notices_values()[ $notice_type ]['url'] ?? '';

		return $this->response_success(
			array(
				'message' => __( 'Notice Removed!', 'wc-affiliate' ),
				'url'     => $url,
			)
		);
	}

	/**
	 * Resolve required dependency.
	 *
	 * Install or activate required dependent plugin.
	 *
	 * @since 1.0.0
	 *
	 * @return bool|WP_Error The response with installation result.
	 */
	public function resolve_required_dependency() {
		$plugin_slug = wca_get_platform();

		// Define plugin file paths.
		$plugin_files = array(
			'woocommerce'  => 'woocommerce/woocommerce.php',
			'easycommerce' => 'easycommerce/easycommerce.php',
		);

		$plugin_file = $plugin_files[ $plugin_slug ];

		// Check if plugin is installed but not active.
		$all_plugins = get_plugins();

		if ( ! isset( $all_plugins[ $plugin_file ] ) ) {
			$result = wca_install_plugin( $plugin_slug, $plugin_file );
			if ( is_wp_error( $result ) ) {
				return new WP_Error( 'wc-affiliate-dep-installation-failed', $result->get_error_message() );
			}
		}

		$result = activate_plugin( $plugin_file );
		if ( is_wp_error( $result ) ) {
			return new WP_Error( 'wc-affiliate-dep-activation-failed', $result->get_error_message() );
		}

		return true;
	}
}
