<?php
function url_replace_run($old_url, $new_url) {
    global $wpdb;

    echo '<div class="updated notice"><p><strong>Replacing ' . esc_html($old_url) . ' with ' . esc_html($new_url) . '</strong></p></div>';

    $tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);

    foreach ($tables as $table) {
        $table_name = $table[0];
        // Escape table name safely for SQL
        $table_name_esc = esc_sql($table_name);

        $columns = $wpdb->get_results("SHOW COLUMNS FROM `{$table_name_esc}`");

        foreach ($columns as $column) {
            $col_name = $column->Field;
            $col_type = strtolower($column->Type);

            if (strpos($col_type, 'char') !== false || strpos($col_type, 'text') !== false) {
                $col_name_esc = esc_sql($col_name);

                $sql = "UPDATE `{$table_name_esc}` SET `{$col_name_esc}` = REPLACE(`{$col_name_esc}`, %s, %s)";
                $query = $wpdb->prepare($sql, $old_url, $new_url);

                $result = $wpdb->query($query);

                if ($result === false) {
                    echo '<div class="error notice"><p>Error updating table ' . esc_html($table_name) . ', column ' . esc_html($col_name) . '</p></div>';
                }
            }
        }
    }

    echo '<div class="updated notice"><p><strong>URL replacement completed.</strong></p></div>';
}
