<?php
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() {
    ?>
    <div class="wrap">
        <h1>URL Replace</h1>
        <form method="post">
            <?php 
            settings_fields('url_replace_group'); 
            wp_nonce_field('url_replace_action', 'url_replace_nonce');
            ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row">Old URL</th>
                    <td>
                        <input type="text" name="old_url" required style="width: 400px;" 
                               value="<?php echo isset($_POST['old_url']) ? esc_attr( sanitize_text_field( wp_unslash( $_POST['old_url'] ) ) ) : ''; ?>">
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row">New URL</th>
                    <td>
                        <input type="text" name="new_url" required style="width: 400px;" 
                               value="<?php echo isset($_POST['new_url']) ? esc_attr( sanitize_text_field( wp_unslash( $_POST['new_url'] ) ) ) : ''; ?>">
                    </td>
                </tr>
            </table>
            <?php submit_button('Replace Now'); ?>
        </form>
        <?php
        if ( isset($_SERVER['REQUEST_METHOD']) && $_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' ) ) {

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

                if ($old_url && $new_url) {
                    url_replace_run($old_url, $new_url);
                } else {
                    echo '<div class="error notice"><p>Both Old URL and New URL are required.</p></div>';
                }
            } else {
                echo '<div class="error notice"><p>Security check failed. Please try again.</p></div>';
            }
        }
        ?>
    </div>
    <?php
}
