<?php
/**
 * Uninstall plugin
 *
 * @package BubblaV_Chat
 */

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

/**
 * Encrypt API key using WordPress AUTH_KEY.
 *
 * @param string $api_key API key to encrypt.
 * @return string Encrypted API key.
 */
function bubblav_encrypt_api_key( $api_key ) {
	if ( ! defined( 'AUTH_KEY' ) || ! defined( 'AUTH_SALT' ) ) {
		return base64_encode( $api_key ); // Fallback to base64 if keys not defined.
	}
	$key = AUTH_KEY;
	$iv  = substr( hash( 'sha256', AUTH_SALT ), 0, 16 );
	$encrypted = openssl_encrypt( $api_key, 'AES-256-CBC', $key, 0, $iv );
	return $encrypted ? base64_encode( $encrypted ) : base64_encode( $api_key );
}

/**
 * Decrypt API key using WordPress AUTH_KEY.
 *
 * @param string $encrypted Encrypted API key.
 * @return string Decrypted API key.
 */
function bubblav_decrypt_api_key( $encrypted ) {
	if ( ! defined( 'AUTH_KEY' ) || ! defined( 'AUTH_SALT' ) ) {
		return base64_decode( $encrypted ); // Fallback to base64 if keys not defined.
	}
	$key = AUTH_KEY;
	$iv  = substr( hash( 'sha256', AUTH_SALT ), 0, 16 );
	$decoded = base64_decode( $encrypted );
	if ( $decoded === false ) {
		return '';
	}
	$decrypted = openssl_decrypt( $decoded, 'AES-256-CBC', $key, 0, $iv );
	return $decrypted !== false ? $decrypted : '';
}

// API endpoint for uninstall notification.
define( 'BUBBLAV_UNINSTALL_API_URL', 'https://www.bubblav.com/api/integrations/wordpress-plugin/uninstall' );

// Check if we should delete plugin data.
// Option to keep data on uninstall can be added via filter.
$bubblav_delete_data = apply_filters( 'bubblav_delete_data_on_uninstall', true );

if ( $bubblav_delete_data ) {
	// Get website ID, site URL, and auth token before deleting options.
	$bubblav_website_id = get_option( 'bubblav_website_id', '' );
	$bubblav_site_url   = get_option( 'bubblav_site_url', home_url() );
	$bubblav_auth_token = get_option( 'bubblav_auth_token', '' );

	// Notify BubblaV about the uninstall.
	if ( ! empty( $bubblav_website_id ) && ! empty( $bubblav_auth_token ) ) {
		bubblav_notify_uninstall( $bubblav_website_id, $bubblav_site_url, $bubblav_auth_token );
	}

	// Delete plugin options.
	delete_option( 'bubblav_website_id' );
	delete_option( 'bubblav_connection_status' );
	delete_option( 'bubblav_site_url' );
	delete_option( 'bubblav_site_name' );
	delete_option( 'bubblav_is_woocommerce' );
	delete_option( 'bubblav_auth_token' );

	// Delete transients.
	delete_transient( 'bubblav_settings_errors' );
	delete_transient( 'bubblav_oauth_state' );

	// Clear any scheduled hooks.
	wp_clear_scheduled_hook( 'bubblav_cleanup_expired_oauth' );
}

/**
 * Notify BubblaV about plugin uninstall.
 *
 * @param string $website_id Website ID.
 * @param string $site_url   Site URL.
 * @param string $auth_token Encrypted auth token (unique per installation).
 * @return void
 */
function bubblav_notify_uninstall( $website_id, $site_url, $auth_token ) {
	// Decrypt auth token.
	$token = bubblav_decrypt_api_key( $auth_token );
	if ( empty( $token ) ) {
		return;
	}

	$body = array(
		'website_id'    => $website_id,
		'site_url'      => $site_url,
		'uninstalled_at' => current_time( 'c' ), // ISO 8601 format.
	);

	$args = array(
		'body'    => wp_json_encode( $body ),
		'headers' => array(
			'Content-Type'  => 'application/json',
			'Authorization' => 'Bearer ' . $token,
		),
		'timeout' => 15, // 15 seconds timeout.
	);

	$response = wp_remote_post( BUBBLAV_UNINSTALL_API_URL, $args );
}
