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

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

global $wpdb;

// Disable foreign key checks
$wpdb->query('SET FOREIGN_KEY_CHECKS = 0');

// Delete ALL ComptaFlow tables
$table_prefix = $wpdb->esc_like($wpdb->prefix . 'cfp_') . '%';
$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
    $wpdb->query("DROP TABLE IF EXISTS `{$table}`");
}

// Re-enable foreign key checks
$wpdb->query('SET FOREIGN_KEY_CHECKS = 1');

// Delete WordPress options
$option_prefix = $wpdb->esc_like('comptaflow_') . '%';
$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
    )
);
