<?php
/**
 * Plugin uninstall handler.
 *
 * @package SubmissionInbox
 */

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

require_once __DIR__ . '/includes/Settings/SettingsRepository.php';
require_once __DIR__ . '/includes/Cloud/SiteIdentity.php';
require_once __DIR__ . '/includes/Cloud/CloudSyncService.php';
require_once __DIR__ . '/includes/Database.php';
require_once __DIR__ . '/includes/Retention/RetentionService.php';
require_once __DIR__ . '/includes/Forms/FormSubmissionContext.php';
require_once __DIR__ . '/includes/MailLog/MailEventRepository.php';
require_once __DIR__ . '/includes/MailLog/MailEventPresenter.php';
require_once __DIR__ . '/includes/MailLog/MailErrorSanitizer.php';
require_once __DIR__ . '/includes/Mail/EmailErrorClassifier.php';
require_once __DIR__ . '/includes/MailLog/EmailLogExportService.php';
require_once __DIR__ . '/includes/Security/Capabilities.php';
require_once __DIR__ . '/includes/Security/TeamAccessService.php';
require_once __DIR__ . '/includes/Lifecycle/SiteProvisioner.php';

// Remove install-namespaced CSVs before deleting their signed metadata. Stop
// while the plugin code still exists if the server refuses private-file cleanup.
$subin_orphan_cleanup = ( new \SUBIN\MailLog\EmailLogExportService(
	new \SUBIN\MailLog\MailEventRepository(),
	new \SUBIN\MailLog\MailEventPresenter()
) )->purge_all_orphan_files();

if ( is_wp_error( $subin_orphan_cleanup ) ) {
	wp_die(
		esc_html( $subin_orphan_cleanup->get_error_message() ),
		esc_html__( 'InboxMend uninstall stopped safely', 'submission-inbox' ),
		array(
			'response'  => 500,
			'back_link' => true,
		)
	);
}

$subin_remove_site = static function () {
	$settings    = get_option( SUBIN_SettingsRepository::OPTION_KEY, array() );
	$delete_data = is_array( $settings ) && ! empty( $settings['delete_data_on_uninstall'] );

	return \SUBIN\Lifecycle\SiteProvisioner::remove_current_site( $delete_data );
};

$subin_cleanup_result = is_multisite()
	? \SUBIN\Lifecycle\SiteProvisioner::for_each_site( $subin_remove_site )
	: $subin_remove_site();

if ( is_wp_error( $subin_cleanup_result ) ) {
	wp_die(
		esc_html__( 'InboxMend could not restore every plugin-managed user permission, so uninstall was stopped before plugin files were removed. Try again after the reported WordPress error is resolved.', 'submission-inbox' ),
		esc_html__( 'InboxMend uninstall stopped safely', 'submission-inbox' ),
		array(
			'response'  => 500,
			'back_link' => true,
		)
	);
}
