<?php

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

function url_replace_recursive($data, $old_url, $new_url) {

    if (is_string($data)) {
        return str_replace($old_url, $new_url, $data);
    }

    if (is_array($data)) {
        foreach ($data as $key => $value) {
            $data[$key] = url_replace_recursive($value, $old_url, $new_url);
        }
    }

    if (is_object($data)) {
        foreach ($data as $key => $value) {
            $data->$key = url_replace_recursive($value, $old_url, $new_url);
        }
    }

    return $data;
}

function url_replace_run($old_url, $new_url) {

    global $wpdb;

    if (!current_user_can('manage_options')) {
        return;
    }

    echo '<div class="notice notice-info"><p><strong>Processing URL replacement...</strong></p></div>';

    $tables = $wpdb->get_col('SHOW TABLES');

    foreach ($tables as $table_name) {

        $columns = $wpdb->get_results("SHOW COLUMNS FROM `$table_name`");

        foreach ($columns as $column) {

            $column_name = $column->Field;
            $column_type = strtolower($column->Type);

            if (
                strpos($column_type, 'char') === false &&
                strpos($column_type, 'text') === false &&
                strpos($column_type, 'longtext') === false
            ) {
                continue;
            }

            $rows = $wpdb->get_results("SELECT * FROM `$table_name`", ARRAY_A);

            foreach ($rows as $row) {

                if (!isset($row[$column_name])) {
                    continue;
                }

                $original_value = $row[$column_name];

                if (empty($original_value)) {
                    continue;
                }

                $updated_value = maybe_unserialize($original_value);

                $updated_value = url_replace_recursive($updated_value, $old_url, $new_url);

                $updated_value = maybe_serialize($updated_value);

                if ($updated_value !== $original_value) {

                    $primary_key = array_key_first($row);

                    $wpdb->update(
                        $table_name,
                        array(
                            $column_name => $updated_value
                        ),
                        array(
                            $primary_key => $row[$primary_key]
                        )
                    );
                }
            }
        }
    }

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