<?php
/** Uninstall for AnyWareX Clone Translate */
if (!defined('WP_UNINSTALL_PLUGIN')) {
  exit;
}

global $wpdb;

/**
 * Helpers
 */
function awxct_delete_options_and_cache(): void
{
  // Aktuelle Options (Client-Seite)
  delete_option('awxct_license_key');
  delete_option('awxct_license_plan');
  delete_option('awxct_license_expire');
  delete_option('awxct_license_status');

  // Legacy / frühere Keys
  delete_option('awxct');  // alter, serialisierter Sammel-Eintrag
  delete_option('awxct_license');
  delete_option('awxct_license_key');
  delete_option('awxct_license_status');
  delete_option('awxct_default_language');
  delete_option('awxct_switcher_label_style');
  delete_option('awxct_json_config');

  // Transients / Cache
  if (function_exists('delete_transient')) {
    delete_transient('awxct_verify_cache');
  }
  if (function_exists('wp_cache_delete')) {
    wp_cache_delete('config', 'awxct');
  }

  // Einzel-Site: Cron räumen
  if (function_exists('wp_next_scheduled') && function_exists('wp_unschedule_event')) {
    $ts = wp_next_scheduled('awxct_license_cron');
    if ($ts) {
      wp_unschedule_event($ts, 'awxct_license_cron');
    }
  }
}

function awxct_drop_tables_for_prefix(string $prefix): void
{
  global $wpdb;

  // Prefix kommt aus WPDB, aber Plugin Check mag trotzdem keine "ungeprüften" Identifiers.
  $prefix = (string) $prefix;

  $tbl_languages    = esc_sql($prefix . 'awxct_languages');
  $tbl_translations = esc_sql($prefix . 'awxct_translations');

  // DROP TABLE ist bei uninstall normal. Das sind bewusst direkte Queries.
  // phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
  $wpdb->query("DROP TABLE IF EXISTS `{$tbl_languages}`");

  // phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
  $wpdb->query("DROP TABLE IF EXISTS `{$tbl_translations}`");

  // phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
}

function awxct_delete_i18n_files(): void
{
  $plugin_dir = plugin_dir_path(__FILE__);
  $i18n_dir   = trailingslashit($plugin_dir . 'i18n');

  if (!is_dir($i18n_dir)) {
    return;
  }

  // Bevorzugt: WP_Filesystem verwenden
  if (!function_exists('WP_Filesystem')) {
    require_once ABSPATH . 'wp-admin/includes/file.php';
  }

  global $wp_filesystem;
  if (empty($wp_filesystem)) {
    WP_Filesystem();
  }

  if ($wp_filesystem instanceof WP_Filesystem_Base) {
    // JSON-Dateien und index.html entfernen
    $files = glob($i18n_dir . '*.json') ?: [];
    foreach ($files as $file) {
      $wp_filesystem->delete($file);
    }

    if ($wp_filesystem->exists($i18n_dir . 'index.html')) {
      $wp_filesystem->delete($i18n_dir . 'index.html');
    }

    // Verzeichnis rekursiv löschen
    $wp_filesystem->delete($i18n_dir, true, 'd');
    return;
  }

  // Fallback: klassische Funktionen, aber WPCS-sicher via wp_delete_file.
  $files = glob($i18n_dir . '*.json') ?: [];
  foreach ($files as $file) {
    wp_delete_file($file);
  }

  if (file_exists($i18n_dir . 'index.html')) {
    wp_delete_file($i18n_dir . 'index.html');
  }

  $left = is_dir($i18n_dir) ? array_diff(scandir($i18n_dir) ?: [], ['.', '..']) : [];
  if (empty($left)) {
    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
    @rmdir($i18n_dir);
  }
}

/** Flags */
$awxct_drop_tables      = defined('AWXCT_DROP_TABLES_ON_UNINSTALL') && AWXCT_DROP_TABLES_ON_UNINSTALL;
$awxct_delete_i18n_json = defined('AWXCT_DELETE_I18N_FILES_ON_UNINSTALL') && AWXCT_DELETE_I18N_FILES_ON_UNINSTALL;

/** Cron-Safety (Klassenbasiert) */
if (class_exists('AWXCT_License') && method_exists('AWXCT_License', 'clear_cron')) {
  try {
    AWXCT_License::clear_cron();
  } catch (\Throwable $e) {
    // Silence on uninstall
  }
}

/** Single- oder Multisite */
if (is_multisite()) {
  $awxct_site_ids = get_sites(['fields' => 'ids']);
  foreach ($awxct_site_ids as $awxct_site_id) {
    switch_to_blog((int) $awxct_site_id);
    awxct_delete_options_and_cache();
    if ($awxct_drop_tables) {
      awxct_drop_tables_for_prefix($wpdb->prefix);
    }
    restore_current_blog();
  }

  // Network-weite Optionen / Transients / Cron
  delete_site_option('awxct_license_key');
  delete_site_option('awxct_license_status');
  delete_site_option('awxct_license_key');
  delete_site_option('awxct_license_plan');
  delete_site_option('awxct_license_expire');
  delete_site_option('awxct_license_status');
  delete_site_option('awxct');

  if (function_exists('delete_site_transient')) {
    delete_site_transient('awxct_verify_cache');
  }
  if (function_exists('wp_clear_scheduled_hook')) {
    wp_clear_scheduled_hook('awxct_license_cron');
  }
} else {
  awxct_delete_options_and_cache();
  if ($awxct_drop_tables) {
    awxct_drop_tables_for_prefix($wpdb->prefix);
  }
}

/** i18n-Dateien löschen? */
if ($awxct_delete_i18n_json) {
  awxct_delete_i18n_files();
}
