<?php

namespace PostenBringCheckout\includes;

use Exception;
use PostenBringCheckout\admin\bring\CheckoutApi;
use PostenBringCheckout\admin\bring\CredentialsService;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Plugin activation
 *
 * Class responsible for handling plugin activation, deactivation and uninstall tasks
 *
 * @since 0.0.1
 */
class Activation {

	/**
	 * Activate plugin
	 *
	 * This function will run plugin activation tasks
	 *
	 * @since 0.0.1
	 */
	public static function activate() {}

	/**
	 * Deactivate plugin
	 *
	 * This function will run plugin deactivation tasks
	 *
	 * @since 0.0.1
	 */
	public static function deactivate() {
	}

	/**
	 * Uninstall plugin
	 *
	 * This function will run plugin uninstallation tasks
	 *
	 * @since 0.0.1
	 */
	public static function uninstall(): void {
		try {
			$credentials = CredentialsService::get_instance()->get_credentials_and_webshop_id();
			$uninstallReason = array();

			if ( ! empty( $credentials->webshop_id ) && ! empty( $credentials->apikey ) ) {
				try {
					$reason = get_option( 'posten-bring-checkout-deactivation-reason' );
					$feedback = get_option( 'posten-bring-checkout-deactivation-feedback' );

					if ( ! empty( $reason ) ) {
						$uninstallReason['reason'] = $reason;
					}

					if ( ! empty( $feedback ) ) {
						$uninstallReason['feedback'] = $feedback;
					}
				} catch ( Exception $e ) {
					wc_get_logger()->warning(
						'Could not collect feedback during uninstallation ' . esc_html($e->getMessage()),
						array(
							'source'    => 'posten-bring-checkout'
						)
					);
				}

				CheckoutApi::get_instance()->uninstallWebshop(
					$credentials->apikey,
					$credentials->webshop_id,
					$uninstallReason
				);

				delete_option( 'posten-bring-checkout-deactivation-reason' );
				delete_option( 'posten-bring-checkout-deactivation-feedback' );
			}

			CredentialsService::get_instance()->remove_credentials();
		} catch ( Exception $e ) {
			wc_get_logger()->error(
				'Could not perform uninstallation tasks. ' . esc_html($e->getMessage()),
				array(
					'source'    => 'posten-bring-checkout',
					'backtrace' => true,
				)
			);
		}
	}
}
