<?php

add_action('init', function () {

    /**
     * Reset the authentication token
     */
    if(
        current_user_can('administrator') &&
        isset($_POST['wpdav_token_reset']) &&
        $_GET['page'] == 'wpdav-settings'

    ) {
        wpdav_reset_auth_token();
    }

    /**
     * Impersonate the user
     */
    if(
        isset($_GET['wpdav-impersonate']) &&
        $_GET['wpdav-impersonate'] &&
        isset($_GET['wpdav-token']) &&
        wpdav_validate_token($_GET['wpdav-token'])
    ) {
        if(wpdav_impersonate_admin()) {
            wp_redirect("/wp-admin");
            exit;
        }
    }

});

/**
 * Register the WPDAV settings page
 */
add_action('admin_menu', function () {
    add_menu_page(
        __('WPDAV Settings page', 'my-textdomain'),
        __('WPDAV', 'my-textdomain'),
        'manage_options',
        'wpdav-settings',
        'wpdav_admin_page_contents',
        'dashicons-schedule',
        3
    );

});

function wpdav_admin_page_contents()
{
    ?>
<form action="" method="post" class="form-example">
    <table class="form-table">
        <tr>
            <th><label for="text">User token</label></th>
            <td>
                <?php echo wpdav_get_auth_token(); ?>
            </td>
        </tr>
        <tr>
            <th><button type="text" id="reset" name="wpdav_token_reset">Generate new token</button></th>
        </tr>
    </table>
</form>

<?php
}
?>