<?php

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

function url_replace_menu() {

    add_menu_page(
        'URL Replace',
        'URL Replace',
        'manage_options',
        'url-replace',
        'url_replace_page',
        'dashicons-admin-links',
        99
    );
}

add_action('admin_menu', 'url_replace_menu');

function url_replace_page() {

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

    ?>
    <div class="wrap">

        <h1>URL Replace</h1>

        <p>
            This tool safely replaces old URLs with new URLs across your WordPress database.
        </p>

        <form method="post">

            <?php wp_nonce_field('url_replace_action', 'url_replace_nonce'); ?>

            <table class="form-table">

                <tr>
                    <th scope="row">Old URL</th>
                    <td>
                        <input
                            type="url"
                            name="old_url"
                            required
                            class="regular-text"
                            placeholder="https://oldsite.com"
                        >
                    </td>
                </tr>

                <tr>
                    <th scope="row">New URL</th>
                    <td>
                        <input
                            type="url"
                            name="new_url"
                            required
                            class="regular-text"
                            placeholder="https://newsite.com"
                        >
                    </td>
                </tr>

            </table>

            <?php submit_button('Replace URLs'); ?>

        </form>

        <?php

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {

            if (
                !isset($_POST['url_replace_nonce']) ||
                !wp_verify_nonce(
                    sanitize_text_field(wp_unslash($_POST['url_replace_nonce'])),
                    'url_replace_action'
                )
            ) {

                echo '<div class="notice notice-error"><p>Security verification failed.</p></div>';
                return;
            }

            $old_url = isset($_POST['old_url'])
                ? esc_url_raw(wp_unslash($_POST['old_url']))
                : '';

            $new_url = isset($_POST['new_url'])
                ? esc_url_raw(wp_unslash($_POST['new_url']))
                : '';

            if (empty($old_url) || empty($new_url)) {

                echo '<div class="notice notice-error"><p>Both URLs are required.</p></div>';
                return;
            }

            url_replace_run($old_url, $new_url);
        }

        ?>

    </div>
    <?php
}
