<?php

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

function sabriel_ai_disinstalla_sito() {
	global $wpdb;

	$impostazioni               = get_option( 'sabriel_ai_settings', [] );
	$elimina_anche_dati_clienti = is_array( $impostazioni ) && ! empty( $impostazioni['elimina_dati_alla_disinstallazione'] );

	delete_option( 'sabriel_ai_settings' );
	delete_option( 'sabriel_gemini_api_key' );
	delete_option( 'sabriel_openai_api_key' );
	delete_option( 'sabriel_claude_api_key' );
	delete_option( 'sabriel_mailchimp_api_key' );
	delete_option( 'sab_dash_last_viewed_sabriel_booking' );
	delete_option( 'sab_dash_last_viewed_sabriel_preventivo' );
	delete_option( 'sab_dash_last_viewed_sabriel_audit' );

	delete_option( 'sab_conoscenza_pagine' );
	delete_post_meta_by_key( '_sab_riassunto' );
	delete_post_meta_by_key( '_sab_riassunto_firma' );
	wp_clear_scheduled_hook( 'sab_rinfresca_conoscenza' );

	delete_option( 'sabriel_ai_ultimo_errore_email' );
	delete_option( 'sabriel_ai_ultima_prova_email' );
	delete_option( 'sabriel_ai_freni_attivi' );

	$prefissi = [
		'_transient_sab_',
		'_transient_timeout_sab_',
		'_transient_sabriel_',
		'_transient_timeout_sabriel_',
		'sabriel_',
		'sab_dash_',
		'sab_prev_counter_',
	];
	foreach ( $prefissi as $prefisso ) {
		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
				$wpdb->esc_like( $prefisso ) . '%'
			)
		);
	}

	wp_cache_flush();

	wp_clear_scheduled_hook( 'sabriel_ai_pulizia_transient' );
	wp_clear_scheduled_hook( 'sab_pulizia_transient_scaduti' );
	wp_clear_scheduled_hook( 'sab_controllo_followup_lead' );

	if ( ! $elimina_anche_dati_clienti ) {
		return;
	}

	foreach ( [ 'sabriel_booking', 'sabriel_preventivo', 'sabriel_chatlog', 'sabriel_audit' ] as $tipo_post ) {
		$giri = 0;
		do {
			$ids = $wpdb->get_col(
				$wpdb->prepare(
					"SELECT ID FROM {$wpdb->posts} WHERE post_type = %s LIMIT 100",
					$tipo_post
				)
			);
			foreach ( $ids as $id ) {
				$id = (int) $id;
				foreach ( [ '_sabp_attachment_id', '_saba_attachment_id' ] as $sab_chiave_allegato ) {
					$sab_allegato = get_post_meta( $id, $sab_chiave_allegato, true );
					if ( $sab_allegato ) {
						wp_delete_attachment( (int) $sab_allegato, true );
					}
				}
				wp_delete_post( $id, true );
			}
			$giri++;
		} while ( ! empty( $ids ) && $giri < 1000 );
	}

	$sab_upload = wp_upload_dir();
	if ( empty( $sab_upload['error'] ) ) {
		$sab_cartella = trailingslashit( $sab_upload['basedir'] ) . 'sabriel-ai-privati';
		if ( is_dir( $sab_cartella ) ) {
			foreach ( [ 'index.php', '.htaccess' ] as $sab_guardia ) {
				if ( file_exists( $sab_cartella . '/' . $sab_guardia ) ) {
					wp_delete_file( $sab_cartella . '/' . $sab_guardia );
				}
			}
			$sab_rimasti = @scandir( $sab_cartella ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- alla disinstallazione una cartella non leggibile non deve fermare la pulizia.
			if ( is_array( $sab_rimasti ) && 2 === count( $sab_rimasti ) ) {
				global $wp_filesystem;
				if ( ! $wp_filesystem ) {
					require_once ABSPATH . 'wp-admin/includes/file.php';
					WP_Filesystem();
				}
				if ( $wp_filesystem ) {
					$wp_filesystem->rmdir( $sab_cartella );
				}
			}
		}
	}
}

if ( is_multisite() ) {
	foreach ( get_sites( [ 'fields' => 'ids', 'number' => 0 ] ) as $sabriel_ai_id_sito ) {
		switch_to_blog( $sabriel_ai_id_sito );
		sabriel_ai_disinstalla_sito();
		restore_current_blog();
	}
} else {
	sabriel_ai_disinstalla_sito();
}
