<?php
// IV1 WP Tools – Tabellen AJAX & Funktionen
defined("ABSPATH") || exit;

// ────────────────────────────────────────────────
// Filesystem-Scan Hilfsfunktionen (ADBC-Ansatz)
// ────────────────────────────────────────────────

/**
 * Liest den Plugin-Namen aus dem Plugin-Header.
 */
function iv1wpt_get_plugin_name_from_dir(string $slug): string {
    $main_file = WP_PLUGIN_DIR . '/' . $slug . '/' . $slug . '.php';

    if (file_exists($main_file)) {
        $content = @file_get_contents($main_file, false, null, 0, 4096);
        if ($content && preg_match('/Plugin Name:\s*(.+)/i', $content, $m)) {
            return trim($m[1]);
        }
    }

    // Fallback: alle PHP-Dateien im Root des Plugin-Verzeichnisses nach Header durchsuchen
    $files = glob(WP_PLUGIN_DIR . '/' . $slug . '/*.php') ?: [];
    foreach ($files as $file) {
        $content = @file_get_contents($file, false, null, 0, 4096);
        if ($content && preg_match('/Plugin Name:\s*(.+)/i', $content, $m)) {
            return trim($m[1]);
        }
    }

    return $slug; // Fallback: Slug als Name
}

/**
 * Sucht den Tabellensuffix in allen Plugin-PHP-Dateien.
 * Gibt ['name' => string, 'active' => bool] zurück oder null wenn nichts gefunden.
 * Ergebnis wird pro Request gecacht.
 */
function iv1wpt_find_table_in_plugin_files(string $suffix): ?array {
    if (empty($suffix) || strlen($suffix) < 4) return null;

    // Cache pro Request
    static $cache = [];
    if (array_key_exists($suffix, $cache)) return $cache[$suffix];

    $active_plugins = (array) get_option('active_plugins', []);
    $plugins_dir    = WP_PLUGIN_DIR;

    // Alle Plugin-Verzeichnisse durchsuchen
    $plugin_dirs = glob($plugins_dir . '/*', GLOB_ONLYDIR);
    if (empty($plugin_dirs)) {
        $cache[$suffix] = null;
        return null;
    }

    foreach ($plugin_dirs as $plugin_dir) {
        $slug = basename($plugin_dir);

        // PHP-Dateien im Plugin-Verzeichnis sammeln (max. 3 Ebenen tief)
        $php_files = array_merge(
            glob($plugin_dir . '/*.php') ?: [],
            glob($plugin_dir . '/*/*.php') ?: [],
            glob($plugin_dir . '/*/*/*.php') ?: []
        );

        foreach ($php_files as $file) {
            // Dateien > 2MB überspringen
            if (@filesize($file) > 2 * 1024 * 1024) continue;

            $content = @file_get_contents($file);
            if ($content === false) continue;

            // Suffix im Dateiinhalt suchen
            if (stripos($content, $suffix) !== false) {
                $name = iv1wpt_get_plugin_name_from_dir($slug);

                // Prüfen ob Plugin aktiv ist
                $is_active = false;
                foreach ($active_plugins as $ap) {
                    if (strpos($ap, $slug . '/') === 0) {
                        $is_active = true;
                        break;
                    }
                }

                $result = ['name' => $name, 'active' => $is_active];
                $cache[$suffix] = $result;
                return $result;
            }
        }
    }

    $cache[$suffix] = null;
    return null;
}

// ────────────────────────────────────────────────
// Hilfsfunktion: Plugin-Tabellen-Zuordnung
// Gibt für jede Tabelle zurück: ['owner' => Name, 'active' => bool]
// ────────────────────────────────────────────────
function iv1wpt_get_table_owners(): array {
    global $wpdb;
    $prefix = $wpdb->prefix;

    // WordPress-Core-Tabellen
    $core_tables = [];
    foreach ($wpdb->tables('all') as $table) {
        $core_tables[$table] = 'WordPress Core';
    }

    // Plugin-Prefix → [Label, Plugin-Datei(en)]
    $plugin_map = [

        // ── WooCommerce ───────────────────────────────────────────────────────
        'woocommerce_gzd_'     => ['Germanized for WooCommerce',     ['woocommerce-germanized/woocommerce-germanized.php']],
        'woocommerce_'         => ['WooCommerce',                    ['woocommerce/woocommerce.php']],
        'wc_order_'            => ['WooCommerce HPOS',               ['woocommerce/woocommerce.php']],
        'wc_admin_'            => ['WooCommerce Admin',              ['woocommerce/woocommerce.php']],
        'wc_'                  => ['WooCommerce',                    ['woocommerce/woocommerce.php']],
        'actionscheduler_'     => ['Action Scheduler',               ['woocommerce/woocommerce.php', 'action-scheduler/action-scheduler.php']],
        'wgm_'                 => ['German Market',                  ['woocommerce-german-market/WooCommerce-German-Market.php']],

        // ── SEO ───────────────────────────────────────────────────────────────
        'wpseo_'               => ['Yoast SEO',                      ['wordpress-seo/wp-seo.php', 'wordpress-seo-premium/wp-seo-premium.php']],
        'yoast_'               => ['Yoast SEO',                      ['wordpress-seo/wp-seo.php', 'wordpress-seo-premium/wp-seo-premium.php']],
        'aioseo_'              => ['All in One SEO',                 ['all-in-one-seo-pack/all_in_one_seo_pack.php']],
        'seopress_'            => ['SEOPress',                       ['wp-seopress/seopress.php']],
        'rank_math_'           => ['Rank Math',                      ['seo-by-rank-math/rank-math.php']],
        'seopressor_'          => ['SEOPressor',                     ['seopressor/seopressor.php']],

        // ── Cache & Performance ───────────────────────────────────────────────
        'wp_rocket_'           => ['WP Rocket',                      ['wp-rocket/wp-rocket.php']],
        'w3tc_'                => ['W3 Total Cache',                 ['w3-total-cache/w3-total-cache.php']],
        'wpfc_'                => ['WP Fastest Cache',               ['wp-fastest-cache/wpFastestCache.php']],
        'litespeed_'           => ['LiteSpeed Cache',                ['litespeed-cache/litespeed-cache.php']],
        'sgs_'                 => ['SiteGround Optimizer',           ['sg-cachepress/sg-cachepress.php']],

        // ── Image Optimization ────────────────────────────────────────────────
        'ewwwio_'              => ['EWWW Image Optimizer',           ['ewww-image-optimizer/ewww-image-optimizer.php']],
        'smush_'               => ['Smush',                          ['wp-smushit/wp-smush.php']],
        'imagify_'             => ['Imagify',                        ['imagify/imagify.php']],
        'shortpixel_'          => ['ShortPixel',                     ['shortpixel-image-optimiser/wp-shortpixel.php']],
        'compressx_'           => ['CompressX',                      ['compressx/compressx.php']],

        // ── Übersetzung / Mehrsprachigkeit ────────────────────────────────────
        'icl_'                 => ['WPML / Polylang',                ['sitepress-multilingual-cms/sitepress.php', 'polylang/polylang.php', 'polylang-pro/polylang.php']],
        'trp_'                 => ['TranslatePress',                 ['translatepress-multilingual/index.php']],
        'pll_'                 => ['Polylang',                       ['polylang/polylang.php', 'polylang-pro/polylang.php']],

        // ── Formulare ─────────────────────────────────────────────────────────
        'gf_'                  => ['Gravity Forms',                  ['gravityforms/gravityforms.php']],
        'rg_'                  => ['Gravity Forms (Legacy)',          ['gravityforms/gravityforms.php']],
        'frm_'                 => ['Formidable Forms',               ['formidable/formidable.php']],
        'wpforms_tasks_'       => ['WPForms',                        ['wpforms-lite/wpforms.php', 'wpforms/wpforms.php']],
        'wpforms_'             => ['WPForms',                        ['wpforms-lite/wpforms.php', 'wpforms/wpforms.php']],
        'nf3_'                 => ['Ninja Forms',                    ['ninja-forms/ninja-forms.php']],
        'fluentform_'          => ['Fluent Forms',                   ['fluentform/fluentform.php', 'fluentformpro/fluentformpro.php']],
        'forminator_'          => ['Forminator',                     ['forminator/forminator.php']],
        'cf7_'                 => ['Contact Form 7',                 ['contact-form-7/wp-contact-form-7.php']],
        'formcraft_'           => ['FormCraft',                      ['formcraft3/formcraft3.php']],
        'f12_cf7_'             => ['CF7 Captcha (Formular 12)',      ['cf7-antispam/cf7-antispam.php', 'formular12-cf7-captcha/formular12-cf7-captcha.php']],

        // ── E-Mail & Newsletter ───────────────────────────────────────────────
        'wpmailsmtp_'          => ['WP Mail SMTP',                   ['wp-mail-smtp/wp_mail_smtp.php']],
        'wp_mail_smtp_'        => ['WP Mail SMTP',                   ['wp-mail-smtp/wp_mail_smtp.php']],
        'post_smtp_'           => ['Post SMTP',                      ['post-smtp/postman-smtp.php']],
        'mailpoet_'            => ['MailPoet',                       ['mailpoet/mailpoet.php']],
        'mailchimp_'           => ['Mailchimp',                      ['mailchimp-for-wp/mailchimp-for-wp.php']],
        'mc4wp_'               => ['Mailchimp for WP',               ['mailchimp-for-wp/mailchimp-for-wp.php']],
        'newsletter_'          => ['Newsletter',                     ['newsletter/plugin.php']],
        'newsletter'           => ['Newsletter',                     ['newsletter/plugin.php']],
        'subscribe_reloaded_'  => ['Subscribe to Comments Reloaded', ['subscribe-to-comments-reloaded/subscribe-to-comments-reloaded.php']],
		'wpo365_events'        => ['WPO365 MS Graph Mailer',  	  	 ['wpo365-msgraphmailer/wpo365-msgraphmailer.php']],
		'wpo365_' => [
			'WPO365',
			[
				'wpo365-msgraphmailer/wpo365-msgraphmailer.php',
				'wpo365-login/wpo365-login.php',
				'wpo365/wpo365.php',
				'wpo365-professional/wpo365-professional.php',
				'wpo365-premium/wpo365-premium.php',
				'wpo365-intranet/wpo365-intranet.php',
			]
		],
		'easywpsmtp_'          => ['Easy WP SMTP', ['easy-wp-smtp/easy-wp-smtp.php']],
		'easy_wp_smtp_'        => ['Easy WP SMTP', ['easy-wp-smtp/easy-wp-smtp.php']],
		
		// ── E-Mail Logging ───────────────────────────────────────────────
		'wpml_mails'           => ['WP Mail Logging', ['wp-mail-logging/wp-mail-logging.php']],

        // ── Security ──────────────────────────────────────────────────────────
        'wfls_'                => ['Wordfence Login Security',       ['wordfence/wordfence.php', 'wordfence-login-security/wordfence-login-security.php']],
        'wf_'                  => ['Wordfence',                      ['wordfence/wordfence.php']],
        'aiowps_'              => ['All In One WP Security',         ['all-in-one-wp-security-and-firewall/wp-security.php']],
        'itsec_'               => ['Solid Security / iThemes Security', ['better-wp-security/better-wp-security.php']],
        'cleantalk_'           => ['CleanTalk',                      ['cleantalk-spam-protect/cleantalk.php']],

        // ── DSGVO / Privacy ───────────────────────────────────────────────────
        //'cmplz_'               => ['Complianz',                      ['complianz-gdpr/complianz-gdpr.php']],
		'cmplz_' => [
			'Complianz',
			[
				'complianz-gdpr/complianz-gpdr.php',
				'complianz-gdpr/complianz-gdpr.php',
				'complianz-gdpr/complianz.php',
			]
		],		
		
        'gdpr_'                => ['WP GDPR Compliance',             ['wp-gdpr-compliance/wp-gdpr-compliance.php']],

        // ── Backup & Migration ────────────────────────────────────────────────
        'updraft_'             => ['UpdraftPlus',                    ['updraftplus/updraftplus.php']],
        'backwpup_'            => ['BackWPup',                       ['backwpup/backwpup.php']],
        'duplicator_'          => ['Duplicator',                     ['duplicator/duplicator.php', 'duplicator-pro/duplicator-pro.php']],
        'wpstg_'               => ['WP Staging',                     ['wp-staging/wp-staging.php']],

        // ── Custom Fields ─────────────────────────────────────────────────────
        'acf_'                 => ['Advanced Custom Fields',         ['advanced-custom-fields/acf.php', 'advanced-custom-fields-pro/acf.php']],
        'pods_'                => ['Pods',                           ['pods/init.php']],

        // ── Page Builder ──────────────────────────────────────────────────────
        'elementor_'           => ['Elementor',                      ['elementor/elementor.php']],
        'e_'                   => ['Elementor',                      ['elementor/elementor.php']],

        // ── Slider ────────────────────────────────────────────────────────────
        'revslider_'           => ['Slider Revolution',              ['revslider/revslider.php']],
        'layerslider'          => ['LayerSlider',                    ['LayerSlider/layerslider.php', 'LayerSlider/layerslider/layerslider.php']],

        // ── Analytics & Tracking ──────────────────────────────────────────────
        'monsterinsights_'     => ['MonsterInsights',                ['google-analytics-for-wordpress/googleanalytics.php']],
        'statistics_'          => ['WP Statistics',                  ['wp-statistics/wp-statistics.php']],
        'ga_'                  => ['Google Analytics',               []],
        'b2s_'                 => ['Blog2Social',                    ['blog2social/blog2social.php']],
        'et_social_stats'      => ['Monarch (Elegant Themes)',       []],

        // ── Weiterleitung ─────────────────────────────────────────────────────
        'redirection_'         => ['Redirection',                    ['redirection/redirection.php']],

        // ── Downloads & Dateien ───────────────────────────────────────────────
        'dlm_'                 => ['Download Monitor',               ['download-monitor/download-monitor.php']],
        'dlm_reports_log'      => ['Download Monitor',               ['download-monitor/download-monitor.php']],
        'download_log'         => ['Download Monitor',               ['download-monitor/download-monitor.php']],
        'wpdm_'                => ['WordPress Download Manager',     ['download-manager/download-manager.php']],

        // ── Events ────────────────────────────────────────────────────────────
        'tribe_'               => ['The Events Calendar',            ['the-events-calendar/the-events-calendar.php']],
        'tec_'                 => ['The Events Calendar',            ['the-events-calendar/the-events-calendar.php']],
        'sc_'                  => ['Sugar Calendar',                 ['sugar-calendar-lite/sugar-calendar-lite.php']],

        // ── Buchung / Termine ─────────────────────────────────────────────────
        'bookly_'              => ['Bookly',                         ['bookly-responsive-appointment-booking-tool/main.php']],
        'amelia_'              => ['Amelia',                         ['ameliabooking/ameliabooking.php']],

        // ── Spenden & Verkauf ─────────────────────────────────────────────────
        'give_'                => ['GiveWP',                         ['give/give.php']],
        'edd_'                 => ['Easy Digital Downloads',         ['easy-digital-downloads/easy-digital-downloads.php']],

        // ── Membership ────────────────────────────────────────────────────────
        'pmpro_'               => ['Paid Memberships Pro',           ['paid-memberships-pro/paid-memberships-pro.php']],
        'rcp_'                 => ['Restrict Content Pro',           ['restrict-content-pro/restrict-content-pro.php']],
        'mepr_'                => ['MemberPress',                    ['memberpress/memberpress.php']],
        'swpm_'                => ['Simple WP Membership',           ['simple-membership/simple-wp-membership.php']],

        // ── Affiliate ─────────────────────────────────────────────────────────
        'affwp_'               => ['AffiliateWP',                    ['affiliate-wp/affiliate-wp.php']],

        // ── Community & Forum ─────────────────────────────────────────────────
        'bp_'                  => ['BuddyPress',                     ['buddypress/bp-loader.php']],
        'bbp_'                 => ['bbPress',                        ['bbpress/bbpress.php']],
        'um_'                  => ['Ultimate Member',                ['ultimate-member/ultimate-member.php']],

        // ── LMS / eLearning ───────────────────────────────────────────────────
        'lifterlms_'           => ['LifterLMS',                      ['lifterlms/lifterlms.php']],
        'llms_'                => ['LifterLMS',                      ['lifterlms/lifterlms.php']],
        'learndash_'           => ['LearnDash',                      ['sfwd-lms/sfwd_lms.php']],
        'learnpress_'          => ['LearnPress',                     ['learnpress/learnpress.php']],
        'tva_'                 => ['Thrive Apprentice',              ['thrive-apprentice/thrive-apprentice.php']],

        // ── Gamification & Punkte ─────────────────────────────────────────────
        'mycred_'              => ['myCred',                         ['mycred/mycred.php']],
        'gamipress_'           => ['GamiPress',                      ['gamipress/gamipress.php']],

        // ── Suche ─────────────────────────────────────────────────────────────
        'ep_'                  => ['ElasticPress',                   ['elasticpress/elasticpress.php']],
        'facetwp_'             => ['FacetWP',                        ['facetwp/index.php']],
        'searchwp_'            => ['SearchWP',                       ['searchwp/index.php']],
        'relevanssi_'          => ['Relevanssi',                     ['relevanssi/relevanssi.php']],

        // ── Tabellen ──────────────────────────────────────────────────────────
        'ninja_table_'         => ['Ninja Tables',                   ['ninja-tables/ninja-tables.php']],
        'wpdt_'                => ['WP Data Tables',                 ['wpdatatables/wpdatatables.php']],

        // ── Thrive Themes ─────────────────────────────────────────────────────
        'tve_leads_'           => ['Thrive Leads',                   ['thrive-leads/thrive-leads.php']],
        'tve_'                 => ['Thrive Themes',                  ['thrive-visual-editor/thrive-visual-editor.php']],
        'tcb_api_error_log'    => ['Thrive Themes',                  ['thrive-visual-editor/thrive-visual-editor.php']],

        // ── Jetpack ───────────────────────────────────────────────────────────
        'jetpack_'             => ['Jetpack',                        ['jetpack/jetpack.php']],

        // ── WP-Optimize ───────────────────────────────────────────────────────
        'tm_tasks'             => ['WP-Optimize',                    ['wp-optimize/wp-optimize.php']],
        'tm_taskmeta'          => ['WP-Optimize',                    ['wp-optimize/wp-optimize.php']],

        // ── IV1 eigene Plugins ────────────────────────────────────────────────
        'iv1_pg_'              => ['IV1 Preisgenerator',             ['iv1-preisgenerator/iv1-preisgenerator.php']],
        'iv1_booking_slots'    => ['IV1 Service System',             ['iv1-service-system/iv1-service-system.php']],
        'iv1_claims'           => ['IV1 Service System',             ['iv1-service-system/iv1-service-system.php']],
        'iv1_serials'          => ['IV1 Service System',             ['iv1-service-system/iv1-service-system.php']],

        // ── Sonstige bekannte Plugins ─────────────────────────────────────────
        'pps_'                 => ['Popup Press',                    ['developer-flavor-starter/developer-starter.php']],
        'grp_'                 => ['Google Reviews',                 ['flavor-flavor/flavor.php']],
        'gg_'                  => ['Gallery',                        ['flavor-flavor-starter/flavor-starter.php']],
        'ahm_'                 => ['Starter Helper',                 ['starter-helper/starter-helper.php']],
        'export_page_to_html_' => ['Export Page to HTML',            ['flavor-flavor-starter/flavor-starter.php']],
        'export_urls_'         => ['Export URLs',                    ['flavor-flavor-starter/flavor-starter.php']],
        'affilinker_'          => ['Affilinker',                     []],
        'afflctable_'          => ['Affiliate Link Cloaker',         []],
        'optinrev'             => ['Optin Revolution',               []],
        'wsc_gocodes'          => ['WPNeon GoCodes',                 []],
		
		// ── Datei-Manager ───────────────────────────────────────────────────────────
		'wpfm_backup'          => ['WP File Manager',                ['wp-file-manager/file_folder_manager.php']],
		
    ];

    uksort($plugin_map, static function ($a, $b) {
        return strlen($b) <=> strlen($a);
    });

    // Aktive Plugins laden
    $active_plugins = (array) get_option('active_plugins', []);
    if (is_multisite()) {
        $network_plugins = array_keys((array) get_site_option('active_sitewide_plugins', []));
        $active_plugins  = array_unique(array_merge($active_plugins, $network_plugins));
    }

    // ────────────────────────────────────────────────
    // $wpdb-Introspection
    // ────────────────────────────────────────────────
    $wpdb_exact    = [];
    $wpdb_prefixes = [];

    // Plugin-Properties die fälschlicherweise als Core erkannt werden
    $wpdb_prop_blacklist = [
        'dlm_api_keys',
        'dlm_downloads',
        'dlm_download_versions',
        'dlm_log',
        'dlm_reports',
        'download_log',
    ];

    foreach (get_object_vars($wpdb) as $prop => $value) {
        if (!is_string($value) || empty($value)) continue;
        if (strpos($value, $prefix) !== 0) continue;
        if (in_array($prop, $wpdb_prop_blacklist, true)) continue;

        $wpdb_exact[$value] = $prop;

        $suffix_len = strlen($value) - strlen($prefix);
        if ($suffix_len >= 3) {
            $wpdb_prefixes[$value] = $prop;
        }
    }

    uksort($wpdb_prefixes, static function ($a, $b) {
        return strlen($b) <=> strlen($a);
    });

    // ────────────────────────────────────────────────
    // Zuordnung aufbauen
    // ────────────────────────────────────────────────
    $owners     = [];
    $all_tables = $wpdb->get_col("SHOW TABLES");

    foreach ($all_tables as $table) {
        if (strpos($table, $prefix) !== 0) continue;

        // Core?
        if (isset($core_tables[$table])) {
            $owners[$table] = ['owner' => 'WordPress Core', 'active' => true, 'type' => 'core'];
            continue;
        }

        $suffix = substr($table, strlen($prefix));

        // $wpdb Exakt-Match
        if (isset($wpdb_exact[$table])) {
            $owners[$table] = [
                'owner'  => 'WordPress Core',
                'active' => true,
                'type'   => 'core',
                'note'   => '$wpdb->' . $wpdb_exact[$table],
            ];
            continue;
        }

        // $wpdb Prefix-Match
        $wpdb_prefix_match = false;
        foreach ($wpdb_prefixes as $wpdb_val => $prop) {
            if (strpos($table, $wpdb_val) === 0) {
                $owners[$table] = [
                    'owner'  => 'WordPress Core',
                    'active' => true,
                    'type'   => 'core',
                    'note'   => '$wpdb->' . $prop . ' (Prefix)',
                ];
                $wpdb_prefix_match = true;
                break;
            }
        }
        if ($wpdb_prefix_match) continue;

        // Plugin-Map prüfen
        $matched = false;
        foreach ($plugin_map as $tbl_prefix => $info) {
            if (strpos($suffix, $tbl_prefix) === 0) {
                $label        = $info[0];
                $plugin_files = $info[1];

                $is_active = false;
                if (empty($plugin_files)) {
                    $is_active = true;
                } else {
                    foreach ($plugin_files as $pf) {
                        if (in_array($pf, $active_plugins, true)) {
                            $is_active = true;
                            break;
                        }
                    }
                }

                $owners[$table] = [
                    'owner'  => $label,
                    'active' => $is_active,
                    'type'   => $is_active ? 'plugin' : 'orphan',
                ];
                $matched = true;
                break;
            }
        }

        if (!$matched) {
            // Whitelist prüfen
            $custom         = get_option('iv1wpt_tables_whitelist', '');
            $custom_matched = false;
            if (!empty($custom)) {
                $custom_prefixes = array_filter(array_map('trim', explode("\n", $custom)));
                foreach ($custom_prefixes as $cp) {
                    if (!empty($cp) && strpos($suffix, $cp) === 0) {
                        $owners[$table] = ['owner' => 'Whitelist (' . $cp . ')', 'active' => true, 'type' => 'whitelist'];
                        $custom_matched = true;
                        break;
                    }
                }
            }

            if (!$custom_matched) {
                // ── Filesystem-Scan als Fallback (ADBC-Ansatz) ──────────────
                $fs_match = iv1wpt_find_table_in_plugin_files($suffix);
                if ($fs_match) {
                    $owners[$table] = [
                        'owner'  => $fs_match['name'],
                        'active' => $fs_match['active'],
                        'type'   => $fs_match['active'] ? 'plugin' : 'orphan',
                        'note'   => 'via_file_scan',
                    ];
                } else {
                    // Unbekannt – NICHT löschbar
                    $owners[$table] = ['owner' => __('Unknown', 'iv1-wp-tools'), 'active' => false, 'type' => 'unknown'];
                }
                // ────────────────────────────────────────────────────────────
            }
        }
    }

    return $owners;
}

// ────────────────────────────────────────────────
// AJAX: Tabellen-Übersicht scannen
// ────────────────────────────────────────────────
add_action('wp_ajax_iv1wpt_tables_scan', 'iv1wpt_tables_scan_ajax');
function iv1wpt_tables_scan_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');

    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    global $wpdb;
    $owners = iv1wpt_get_table_owners();
	$iv1wpt_has_pro = iv1wpt_has_pro();

    $statuses = [];
    $results  = $wpdb->get_results("SHOW TABLE STATUS", ARRAY_A);
    foreach ($results as $s) {
        $statuses[$s['Name']] = $s;
    }

    ob_start();

    $orphan_count  = 0;
    $unknown_count = 0;
    $total_tables  = 0;

    foreach ($owners as $table => $info) {
        $total_tables++;
        if ($info['type'] === 'orphan')  $orphan_count++;
        if ($info['type'] === 'unknown') $unknown_count++;
    }

    echo '<p>' . sprintf(
        /* translators: %d: number of tables */
        esc_html__('%d tables found', 'iv1-wp-tools'),
        $total_tables
    );
    if ($orphan_count > 0) {
        echo ', ' . sprintf(
            '<strong style="color:#d63638;">' .
            /* translators: %d: number of orphaned tables */
            esc_html__('%d orphaned', 'iv1-wp-tools') .
            '</strong>',
            $orphan_count
        );
    } else {
        echo ' – <strong style="color:#00a32a;">' . esc_html__('no orphaned tables', 'iv1-wp-tools') . '</strong>';
    }
    if ($unknown_count > 0) {
        echo ', ' . sprintf(
            '<strong style="color:#996800;">' .
            /* translators: %d: number of unknown tables */
            esc_html__('%d unknown', 'iv1-wp-tools') .
            '</strong>',
            $unknown_count
        );
    }
    echo '</p>';

    echo '<table class="widefat striped">';
    echo '<thead><tr>';
    echo '<th style="width:30px;"><input type="checkbox" id="iv1wpt-tables-check-all"></th>';
    echo '<th>' . esc_html__('Table name', 'iv1-wp-tools') . '</th>';
    echo '<th style="width:90px; text-align:right;">' . esc_html__('Rows', 'iv1-wp-tools') . '</th>';
    echo '<th style="width:90px; text-align:right;">' . esc_html__('Size', 'iv1-wp-tools') . '</th>';
    echo '<th style="width:200px;">' . esc_html__('Belongs to', 'iv1-wp-tools') . '</th>';
    echo '<th style="width:100px; text-align:right;">' . esc_html__('Action', 'iv1-wp-tools') . '</th>';
    echo '</tr></thead><tbody>';

    foreach ($owners as $table => $info) {
        $s    = $statuses[$table] ?? [];
        $rows = (int) ($s['Rows'] ?? 0);
        $size = (int) ($s['Data_length'] ?? 0) + (int) ($s['Index_length'] ?? 0);

        if ($info['type'] === 'core') {
            $note  = !empty($info['note']) ? ' <small style="color:#aaa;">(' . esc_html($info['note']) . ')</small>' : '';
            $badge = '<span style="color:#2271b1; font-weight:600;">' . esc_html($info['owner']) . '</span>' . $note;
            $badge .= ' <span class="dashicons dashicons-lock" style="font-size:14px; width:14px; height:14px; color:#999;" title="' . esc_attr__('Protected', 'iv1-wp-tools') . '"></span>';
        } elseif ($info['type'] === 'plugin' || $info['type'] === 'whitelist') {
            $badge  = '<span style="color:#00a32a;">' . esc_html($info['owner']) . '</span>';
            $badge .= '<br><small style="color:#00a32a;">● ' . esc_html__('Active', 'iv1-wp-tools') . '</small>';
            if (!empty($info['note']) && $info['note'] === 'via_file_scan') {
                $badge .= ' <small style="color:#aaa;">(' . esc_html__('file scan', 'iv1-wp-tools') . ')</small>';
            }
        } elseif ($info['type'] === 'orphan') {
            $badge  = '<span style="color:#d63638;">' . esc_html($info['owner']) . '</span>';
            $badge .= '<br><span style="color:#d63638;">' . esc_html__('Orphaned', 'iv1-wp-tools') . '</span>';
            if (!empty($info['note']) && $info['note'] === 'via_file_scan') {
                $badge .= ' <small style="color:#aaa;">(' . esc_html__('file scan', 'iv1-wp-tools') . ')</small>';
            }
        } else {
            // unknown
            $badge  = '<span style="color:#996800;">' . esc_html__('Unknown', 'iv1-wp-tools') . '</span>';
            $badge .= '<br><small style="color:#996800;">⚠ ' . esc_html__('Not assigned', 'iv1-wp-tools') . '</small>';
        }

        // Nur 'orphan' ist löschbar – 'unknown' nicht
        $is_deletable = ($info['type'] === 'orphan');

        echo '<tr data-table="' . esc_attr($table) . '">';
        echo '<td>';
        if ($is_deletable && $iv1wpt_has_pro) {
            echo '<input type="checkbox" class="iv1wpt-table-check" value="' . esc_attr($table) . '">';
        }
        echo '</td>';
        echo '<td><code style="font-size:13px;">' . esc_html($table) . '</code></td>';
        echo '<td style="text-align:right;">' . esc_html(number_format_i18n($rows)) . '</td>';
        echo '<td style="text-align:right;">' . esc_html(size_format($size)) . '</td>';
        echo '<td>' . $badge . '</td>';
        echo '<td style="text-align:right;">';
        if ($is_deletable && $iv1wpt_has_pro) {
            echo '<button type="button" class="button button-small iv1wpt-icon-btn iv1wpt-drop-table" data-table="' . esc_attr($table) . '" title="' . esc_attr__('Delete', 'iv1-wp-tools') . '" aria-label="' . esc_attr__('Delete', 'iv1-wp-tools') . '">';
            echo '<span class="dashicons dashicons-trash" aria-hidden="true"></span>';
            echo '</button>';
		}elseif ($is_deletable && !$iv1wpt_has_pro) {
            echo '<button type="button" class="button button-small iv1wpt-icon-btn iv1wpt-drop-table" data-table="' . esc_attr($table) . '" title="' . esc_attr__('Delete', 'iv1-wp-tools') . '" aria-label="' . esc_attr__('Delete', 'iv1-wp-tools') . '" disabled>';
            echo '<span class="dashicons dashicons-trash" aria-hidden="true"></span>';
            echo '</button>';
		
        }
        echo '</td>';
        echo '</tr>';
    }

    echo '</tbody></table>';

    $html = ob_get_clean();

    wp_send_json_success([
        'html'         => $html,
        'orphan_count' => $orphan_count,
    ]);
}

// ────────────────────────────────────────────────
// Hilfsfunktion: Bekannte Tabellen (für Drop-Schutz)
// ────────────────────────────────────────────────
function iv1wpt_get_known_tables(): array {
    $owners = iv1wpt_get_table_owners();
    $known  = [];
    foreach ($owners as $table => $info) {
        if ($info['type'] !== 'orphan') {
            $known[] = $table;
        }
    }
    return $known;
}

// ────────────────────────────────────────────────
// AJAX: Einzelne Tabelle löschen (DROP)
// ────────────────────────────────────────────────
add_action('wp_ajax_iv1wpt_tables_drop', 'iv1wpt_tables_drop_ajax');
function iv1wpt_tables_drop_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');

    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    if (!iv1wpt_has_pro()) {
        wp_send_json_error(__('Deleting tables requires IV1 WP Tools Pro.', 'iv1-wp-tools'));
    }

    global $wpdb;

    $table = isset($_POST['table_name'])
        ? sanitize_text_field(wp_unslash($_POST['table_name']))
        : '';

    if (empty($table) || !preg_match('/^[A-Za-z0-9_]+$/', $table)) {
        wp_send_json_error(__('Invalid table name', 'iv1-wp-tools'));
    }

    if (strpos($table, $wpdb->prefix) !== 0) {
        wp_send_json_error(__('Invalid table name', 'iv1-wp-tools'));
    }

    $existing_tables = $wpdb->get_col('SHOW TABLES');
    if (!in_array($table, $existing_tables, true)) {
        wp_send_json_error(__('Table does not exist', 'iv1-wp-tools'));
    }

    // Nur 'orphan' darf gelöscht werden – 'unknown' und alle anderen sind geschützt
    $owners = iv1wpt_get_table_owners();
    if (!isset($owners[$table]) || $owners[$table]['type'] !== 'orphan') {
        wp_send_json_error(__('This table cannot be deleted', 'iv1-wp-tools'));
    }

    $safe_table = esc_sql($table);
    $result     = $wpdb->query("DROP TABLE IF EXISTS `{$safe_table}`");

    if ($result !== false) {
		iv1wpt_plugin_log(
			sprintf(
				/* translators: %s: database table name */
				__('IV1WPT: Table deleted → %s', 'iv1-wp-tools'),
				$table
			)
		);		
        wp_send_json_success(sprintf(
            /* translators: %s: table name */
            __('Table %s deleted.', 'iv1-wp-tools'),
            $table
        ));
    }

    wp_send_json_error(sprintf(
        /* translators: %s: table name */
        __('DROP TABLE failed for %s', 'iv1-wp-tools'),
        $table
    ));
}