<?php
/**
 * Uninstall ComptaFlow UK by MeeTempo
 * Removes ALL data (tables + options)
 * 
 * WARNING: This operation is IRREVERSIBLE
 */

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

global $wpdb;

// Disable foreign key checks
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$wpdb->query('SET FOREIGN_KEY_CHECKS = 0');

// Delete ALL ComptaFlow tables
$table_prefix = $wpdb->esc_like($wpdb->prefix . 'cfuk_') . '%';
$tables = $wpdb->get_col(
    $wpdb->prepare(
        "SELECT table_name 
         FROM information_schema.tables 
         WHERE table_schema = DATABASE() 
         AND table_name LIKE %s",
        $table_prefix
    )
);

foreach ($tables as $table) {
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name from database schema query
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
    $wpdb->query("DROP TABLE IF EXISTS `{$table}`");
}

// Re-enable foreign key checks
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$wpdb->query('SET FOREIGN_KEY_CHECKS = 1');

// Delete WordPress options
$option_prefix = $wpdb->esc_like('comptaflow_uk_') . '%';
$wpdb->query(
    $wpdb->prepare(
        "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
        $option_prefix
    )
);

// Delete user meta
$wpdb->query(
    $wpdb->prepare(
        "DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE %s",
        $option_prefix
    )
);
