<?php
/**
 * Fired when the plugin is uninstalled.
 *
 * @package    WPFMJ
 */

// If uninstall not called from WordPress, then exit.
if (!defined('WP_UNINSTALL_PLUGIN')) {
    exit;
}

global $wpdb;

// Delete all automations
$automations = get_posts(array(
    'post_type' => 'wpfmj_automation',
    'post_status' => 'any',
    'posts_per_page' => -1,
    'fields' => 'ids'
));

foreach ($automations as $automation_id) {
    wp_delete_post($automation_id, true);
}

// Drop error log table
// Table name is safe as it uses WordPress prefix + hardcoded suffix
$table_name = $wpdb->prefix . 'wpfmj_error_log';
// Validate table name format to prevent any potential issues
if (preg_match('/^[a-zA-Z0-9_]+$/', $table_name)) {
    $wpdb->query("DROP TABLE IF EXISTS `{$table_name}`");
}

// Delete options
delete_option('wpfmj_version');
delete_option('wpfmj_encryption_key');

// Clear scheduled crons
wp_clear_scheduled_hook('wpfmj_cleanup_error_logs');

// Flush rewrite rules
flush_rewrite_rules();
