<?php
/**
 * Plugin Name: BW Plugin
 * Plugin URI: https://bluewindowltd.com/
 * Description: Blue Window plugin to control WP installations
 * Version: 1.02
 * Author: BlueWindow
 * Author URI: https://bluewindowltd.com/
 */


// Security - disable direct file access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

require_once 'vendor/autoload.php';

use Google\Cloud\Storage\StorageClient;

include_once 'config.php';
include_once 'validation.php';
include_once 'admin/Notices.php';
include_once 'helpers.php';


/**
 * Sets up a JSON endpoint routes at /wp-json/bw/v1/...
 * for all the functions that we are creating
 */
function bw_api_init() {
    $namespace = 'bw/v1';
    register_rest_route( $namespace, '/heartbeat/', array(
        'methods' => 'GET',
        'callback' => 'bw_get_heartbeat',
    ) );    
    register_rest_route( $namespace, '/plugins/', array(
        'methods' => 'GET',
        'callback' => 'bw_get_plugins',
    ) );

    register_rest_route( $namespace, '/themes/', array(
        'methods' => 'GET',
        'callback' => 'bw_get_themes',
    ) );

    register_rest_route( $namespace, '/categories/', array(
        'methods' => 'GET',
        'callback' => 'bw_get_categories',
    ) );

    register_rest_route( $namespace, '/permalinks/', array(
        'methods' => 'GET',
        'callback' => 'bw_get_permalinks',
    ) );

    register_rest_route( $namespace, '/post/', array(
        'methods' => 'POST',
        'callback' => 'bw_post_posts',
    ) );

    register_rest_route( $namespace, '/posts/', array(
        'methods' => 'GET',
        'callback' => 'bw_get_posts',
    ) );

    register_rest_route( $namespace, '/fileupload/', array(
        'methods' => 'POST',
        'callback' => 'bw_post_fileupload',
    ) );

    register_rest_route( $namespace, '/pages/', array(
        'methods' => 'GET',
        'callback' => 'bw_get_pages',
    ) );

    register_rest_route( $namespace, '/deletepage/', array(
        'methods' => 'POST',
        'callback' => 'bw_delete_post',
    ) );

    register_rest_route( $namespace, '/deletepost/', array(
        'methods' => 'POST',
        'callback' => 'bw_delete_post',
    ) );

    register_rest_route( $namespace, '/updatepost/', array(
        'methods' => 'POST',
        'callback' => 'bw_update_post',
    ) );
    
    register_rest_route( $namespace, '/getslug/', array(
    'methods' => 'GET',
    'callback' => 'bw_get_slug',
    ) );

    register_rest_route( $namespace, '/insertcategory/', array(
        'methods' => 'POST',
        'callback' => 'bw_insert_category',
    ) );

    register_rest_route( $namespace, '/getpost/', array(
        'methods' => 'GET',
        'callback' => 'bw_get_post',
    ) );
	
    register_rest_route( $namespace, '/automaticupdate/', array(
        'methods' => 'POST',
        'callback' => 'bw_post_automatic_update',
    ) );

    register_rest_route( $namespace, '/automaticupdateplugin/', array(
        'methods' => 'POST',
        'callback' => 'bw_post_autoupdate_plugin',
    ) );

    register_rest_route( $namespace, '/automaticupdatetheme/', array(
        'methods' => 'POST',
        'callback' => 'bw_post_autoupdate_theme',
    ) );    

    register_rest_route( $namespace, '/disablecomments/', array(
        'methods' => 'POST',
        'callback' => 'bw_post_disable_comments',
    ) );  

    register_rest_route( $namespace, '/statuscomments/', array(
        'methods' => 'GET',
        'callback' => 'bw_get_status_comments',
    ) );  

    register_rest_route( $namespace, '/createuser/', array(
        'methods' => 'POST',
        'callback' => 'bw_post_create_user',
    ) ); 

    register_rest_route( $namespace, '/updateuser/', array(
        'methods' => 'POST',
        'callback' => 'bw_post_update_user',
    ) ); 

    register_rest_route( $namespace, '/addroleuser/', array(
        'methods' => 'POST',
        'callback' => 'bw_post_add_role_user',
    ) );

    register_rest_route( $namespace, '/removeroleuser/', array(
        'methods' => 'POST',
        'callback' => 'bw_post_remove_role_user',
    ) );

    register_rest_route( $namespace, '/checkpluginupdates/', array(
        'methods' => 'GET',
        'callback' => 'bw_check_plugin_updates',
    ) ); 

    register_rest_route( $namespace, '/checkcoreupdates/', array(
        'methods' => 'GET',
        'callback' => 'bw_check_core_updates',
    ) ); 
}

add_action( 'rest_api_init', 'bw_api_init' );

//Remove version generator
remove_action('wp_head', 'wp_generator');


/**
 * 
 * Admin menu
 * 
 */

function bw_plugin_menu(){
    add_menu_page( 'Blue Window Plugin Page', 'BW Plugin', 'manage_options', 'bw-plugin', 'bw_plugin_init' );
}

function bw_plugin_init(){
    include 'admin/index.php';
}

add_action('admin_menu', 'bw_plugin_menu');
add_action('wp_ajax_bw_update_api_key', 'bw_update_api_key');

// -----------------------------------------------------------------------

// this code will run only once on plugin activation and never again
function add_editor_role() {
    add_role(
         'bw_editor',
         'BW Editor Role', 
         array( 
            'delete_others_pages' => true,
            'delete_others_posts' => true,
            'delete_pages'=> true,
            'delete_posts'=> true,
            'delete_private_pages'=> true,
            'delete_private_posts'=> true,
            'delete_published_pages'=> true,
            'delete_published_posts'=> true,
            'delete Reusable Blocks'=> true,
            'edit_others_pages'=> true,
            'edit_others_posts'=> true,
            'edit_pages'=> true,
            'edit_posts'=> true,
            'edit_private_pages'=> true,
            'edit_private_posts'=> true,
            'edit_published_pages'=> true,
            'edit_published_posts'=> true,
            'create Reusable Blocks'=> true,
            'edit Reusable Blocks'=> true,
            'manage_categories'=> true,
            'manage_links'=> true,
            'moderate_comments'=> true,
            'publish_pages'=> true,
            'publish_posts'=> true,
            'read'=> true,
            'read_private_pages'=> true,
            'read_private_posts'=> true,
            'unfiltered_html'=> true,
            'upload_files'=> true,
            'install_themes'=> true,
            'delete_themes'=> true,
            'edit_themes'=> true,
         )
    );
}
// Add the simple_role.
add_action( 'init', 'add_editor_role' );

// -----------------------------------------------------------------------


function bw_update_api_key() {
    $key = $_POST['api_key'];
    Helpers::setBWApiKey($key);
    wp_redirect(admin_url('admin.php?page=bw-plugin'));
    add_flash_notice( __("The API Key has been added successfully."), "warning", true );
    exit();
}


/**
 * Send OK as a heartbeat response
 * Returns back a WP_REST_Response with string OK 
 * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
 */
function bw_get_heartbeat( WP_REST_Request $request ) {
    $response = new WP_REST_Response( "OK" );
    return $response;
}


/**
 * Retrieves all the plugins in the website
 * Returns back a WP_REST_Response with an array of plugins information 
 * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
 */
function bw_get_plugins( WP_REST_Request $request ) {
    // Check if get_plugins() function exists. This is required on the front end of the
    // site, since it is in a file that is normally only loaded in the admin.
    if ( ! function_exists( 'get_plugins' ) ) {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
    }

    $arr_plugins = get_plugins();
    $arr_result = [];

    foreach($arr_plugins as $plugin=>$details){
        $details['Status'] = is_plugin_active($plugin) ? 'Active' :  'Deactivated';
        $details['Filename'] = $plugin;
        $arr_result[] = $details;
    }
    $response = new WP_REST_Response( $arr_result );
    return $response;
}


/**
 * Retrieves all the themes information in the website
 * Returns back a WP_REST_Response with an array of themes information 
 * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
 */
function bw_get_themes( WP_REST_Request $request ) {
    $themes = wp_get_themes();
    $cur_theme_name = wp_get_theme()->get( 'Name' );
    $theme_details = [];

    // Since the theme returns an object with private properties we need
    // to extract the properties and build our own array with required information
    foreach($themes as $t) {
        $parent = $t->parent();
        $theme_details[] = [
            'Name' => $t->get( 'Name' ),
            'Active' => $cur_theme_name == $t->get( 'Name' ) ? 'Active' : 'Not Active',
            'Parent' => !empty($parent) ? $parent->get('Name') : ' ',
            'ThemeURI' => $t->get( 'ThemeURI' ),
            'Version' => $t->get( 'Version' ),
            'Template' => $t->get( 'Template' ),
            'TextDomain' => $t->get( 'TextDomain' )
        ];
    }

    $response = new WP_REST_Response( $theme_details );
    return $response;
}


/**
 * Retrieves all the categories in the website
 * Returns back a WP_REST_Response with an array of Category information 
 * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
 */
function bw_get_categories( WP_REST_Request $request ) {
    // setting args in order to show also not used categories
    $args = array(
        'hide_empty' => 0
    );

    $categories = get_categories($args);
    $response = new WP_REST_Response( $categories );
    return $response;
}


/**
 * Retrieves all the permalinks in the website
 * Returns back a WP_REST_Response with an array 
 * of permalinks information 
 * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
 */
function bw_get_permalinks( WP_REST_Request $request ) {
    $output_arr = [];
    // We need to loop through the posts in order to get the permalinks of all posts
    $args = array('post_type' => 'post', 'posts_per_page' => -1 ); 
    $loop = new WP_Query($args); 
    if( $loop->have_posts() ): 
        while( $loop->have_posts() ): 
            $loop->the_post(); 
            global $post; 
            $output_arr[] = [
                'post_id' => $post->ID,
                'permalink' => get_permalink($post->ID),
            ];
        endwhile; 
    endif; 
    wp_reset_query();
    $response = new WP_REST_Response( $output_arr );
    return $response;
}



/**
 * Posts a post on the WP website
 * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
*/
function bw_post_posts( WP_REST_Request $request ) {
    $post = $request->get_params();
    $api_key = $post['api_key'];

    $validation_errors = Validation::validate_post($post);

     if (! empty($validation_errors)) {
         return new WP_REST_Response( $validation_errors );
     }

    $postData = [
        'post_status' => $post['status'],
        'post_author' => $postAuthorId,
        'post_title' => $post['title'],
        'post_content' => $post['body'],
        'post_type' => $post['type'],
        'post_category_name' => ! empty( $post['category'] ) ? $post['category'] : '',
        'post_publish_at' => ! empty( $post['publish_at'] ) ? $post['publish_at'] : '',
    ]; 

    // post_category is string
    if (! empty($postData['post_category_name'])) {
        $term = term_exists($postData['post_category'], 'category');

        // if category exists then we have id in $term else we need to create it and 
        // insert the new category getting the new term id
        if (! $term) {
            $term = wp_insert_term($postData['post_category'], 'category');
        }

        // we set post_category id from the retireved term
        if (! empty($term['term_id'])) {
            $postData['post_category'] = [$term['term_id']];
        }
    }

    $postId = wp_insert_post( $postData );

    if ($postId === 0) {
        $msg = [
            'error' => "Error while creating a post, request_id: { $postId }"
        ];
    } else {
        $msg = [
            'success' => "Post created successfully",
            'id' => $postId
        ];
    }

    $response = new WP_REST_Response( $msg );    
    return $response;
}


/**
 * Get available posts from the WP website
 * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
*/
function bw_get_posts(WP_REST_Request $request) {
    $get = $request->get_params();
    $args = array(
        'post_status' => get_post_stati() // publish or draft, default set to everything
      );

    $args = isset($get['name']) ? array_merge($args, ['name' => $get['name']]) : $args;
    $args = isset($get['post_status']) ? array_merge($args, ['post_status' => $get['post_status']]) : $args;
    $args = isset($get['numberposts']) ? array_merge($args, ['numberposts' => $get['numberposts']]) : $args;

    $reponse = new WP_REST_Response(get_posts($args));
    return $reponse;
}



/**
 * Get available pages from the WP website
 * 
 * @param WP_REST_Request $request
 * @return array $response 
*/
function bw_get_pages(WP_REST_Request $request) {
    $get = $request->get_params();
    $args = array(
       'post_status' => get_post_stati() // gets all post_statuses, default set to everything
      );
    
    $args = isset($get['post_status']) ? array_merge($args, ['post_status' => $get['post_status']]) : $args;
    $args = isset($get['numberposts']) ? array_merge($args, ['number' => $get['numberposts']]) : $args;
    
    $response = new WP_REST_Response(get_pages($args));
    return $response;
}


/**
 * Delete post or page
 * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
*/
function bw_delete_post(WP_REST_Request $request) {
    $post = $request->get_params();
    $api_key = $post['api_key'];

    $validation_errors = Validation::validate_api_key($api_key);
    if (! empty($validation_errors)) {
        return new WP_REST_Response( $validation_errors );
    }

    $post_id = $post['post_id'];
    $force_delete = $post['force_delete'];
    $del_post = wp_delete_post($post_id, $force_delete);
    $res = empty($del_post)?'Post cannot be deleted':'Post has been deleted';
    $reponse = new WP_REST_Response($res);
    return $response;
}


/**
 * Update post or page
 * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
*/
function bw_update_post(WP_REST_Request $request) {
    $post = $request->get_params();

    $validation_errors = Validation::validate_api_key($api_key);
    if (! empty($validation_errors)) {
        return new WP_REST_Response( $validation_errors );
    }

    $args = [];
    $args = isset($post['post_id']) ? array_merge($args, ['ID' => $post['post_id']]) : $args;
    $args = isset($post['post_title']) ? array_merge($args, ['post_title' => $post['post_title']]) : $args;
    $args = isset($post['post_content']) ? array_merge($args, ['post_content' => $post['post_content']]) : $args;
    $args = isset($post['post_status']) ? array_merge($args, ['post_status' => $post['post_status']]) : $args;

    // Update the post into the database
    $response = wp_update_post( $args );
    // $reponse = new WP_REST_Response($response);
    
    if ($response == 0) {
        $msg = "There has been an error";
    } else {
        $msg = "Successfully updated post id " . $response;
    }

    return $msg;
}


/**
 * Upload File on the WP website
 * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
*/
function bw_post_fileupload( WP_REST_Request $request) {
    // $files = ($request->get_file_params()); 
    $files = ($request->get_params());   
    $ret_msg= [];

    foreach ($files as $file) {
        $target_dir = $file["target_folder"];
        $base_dir =  wp_upload_dir()['basedir'];
        $target_location = empty($target_dir) ? $base_dir : $base_dir . "/" . $target_dir; 
        $target_file = $target_location . "/" . basename($file["name"]);

        $file_validation = (Validation::validate_image($file));

        if (empty($file_validation)) {
            if (!file_exists($target_location) && !mkdir($target_location, 0705, true)) {
                return ["Failed to create folder : " . $target_dir];
            }

            $overwritten = "";
            if (file_exists($target_file)) {
                chmod($target_file, 0755); //Change the file permissions if allowed
                unlink($target_file); //remove the file
                $overwritten = "File has been replaced.";
            }        

            if (Helpers::base64ToImage($file['file'], $target_file)) {
                $ret_msg[] = $file["name"] . " (" . $target_file . ") has been uploaded." . " " . $overwritten;
            } else {
                $ret_msg[] = $file['name'] . " cannot be uploaded.";
            }
        } else {
            $ret_msg = array_merge($ret_msg, $file_validation);
        }
    }

    $response = new WP_REST_Response($ret_msg); 
    return $response;
}



/**
 * Get the id of the author
 * 
 * @param $author
 * @return int $user->ID
*/
function getAuthorId( $author = null )
{
    $users = get_users(['orderby' => 'id']);
    foreach ($users as $user) {
        return $user->ID;
    }
}


/**
 * Get post slug
 * 
 * @param int $post_id
 * @return string preview link
 */
function bw_get_slug(WP_REST_Request $request)
{
    $req = $request->get_params();	
    $post_id = $req['post_id'];
    $post = get_post($post_id); 
    $slug = $post->post_name;
	if (empty($slug)) {
        $slug  = sanitize_title( $post->post_title );
    }
    return $slug;
}


/**
 * Update or insert category
 * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
*/
function bw_insert_category(WP_REST_Request $request) 
{
	if ( ! function_exists( 'wp_insert_category' ) ) {
        require_once( ABSPATH . '/wp-admin/includes/taxonomy.php');
    }
	
    $post = $request->get_params();
	$api_key = $post['api_key'];
    $validation_errors = Validation::validate_api_key($api_key);
    if (! empty($validation_errors)) {
        return new WP_REST_Response( $validation_errors );
    }

    $category = [];
    // A non-zero value updates an existing category. Default 0.
    $category = isset($post['category_ID']) ? array_merge($category, ['cat_ID' => $post['category_ID']]) : $category;
    $category = isset($post['taxonomy']) ? array_merge($category, ['taxonomy' => $post['taxonomy']]) : $category; // default 'category'
    $category = isset($post['category_name']) ? array_merge($category, ['cat_name' => $post['category_name']]) : $category; // default empty
    $category = isset($post['category_description']) ? array_merge($category, ['category_description' => $post['category_description']]) : $category; // default empty
    $category = isset($post['category_nicename']) ? array_merge($category, ['category_nicename' => $post['category_nicename']]) : $category; // default empty
    $category = isset($post['category_parent']) ? array_merge($category, ['category_parent' => $post['category_parent']]) : $category;

    $response = wp_insert_category( $category );
    // $reponse = new WP_REST_Response($response);
    
    if ($response == 0) {
        $msg = "There has been an error";
    } else {
        $msg = "Successfully inserted category ID:" . $response;
    }

    return $msg;
}

/**
 * Get available post from the WP website
 * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
*/
function bw_get_post(WP_REST_Request $request) {
    $get = $request->get_params();
    $args = [];

    $args = isset($get['id']) ? $get['id'] : '';
    $reponse =  get_post($args);
    //return parse_blocks($reponse->post_content);
	return $reponse->post_content;
}



/**
 * Enable / disable automatic updates
 * ALL type of updates
 * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
*/
function bw_post_automatic_update(WP_REST_Request $request) {
    $post = $request->get_params();
    $api_key = $post['api_key'];
    
    $validation_errors = Validation::validate_api_key($api_key);
    if (! empty($validation_errors)) {
        return new WP_REST_Response( $validation_errors );
    }
    $update = isset($post['update']) ? $post['update'] : '';

    if ($update == 'true') {
        add_filter( 'automatic_updater_disabled', '__return_true' );
        return 'Auto Updater Enabled';

    } else {
        add_filter( 'automatic_updater_disabled', '__return_false' );
        return 'Auto Updater Disabled';
    }
}


/**
 * Enable / disable automatic updates
 * of Plugins
 */
function bw_post_autoupdate_plugin(WP_REST_Request $request) {
    $post = $request->get_params();
    $api_key = $post['api_key'];
    
    $validation_errors = Validation::validate_api_key($api_key);
    if (! empty($validation_errors)) {
        return new WP_REST_Response( $validation_errors );
    }

    $update = isset($post['update']) ? $post['update'] : '';

    if ($update == 'true') {
        add_filter( 'auto_update_plugin', '__return_true' );
        return 'Auto Update Plugin Enabled';
    } else {
        add_filter( 'auto_update_plugin', '__return_false' );
        return 'Auto Update Plugin Disabled';
    }
    
}


/**
 * Enable / disable automatic updates
 * of themes
 * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
 */
function bw_post_autoupdate_theme(WP_REST_Request $request) {
    $post = $request->get_params();
    $api_key = $post['api_key'];
    
    $validation_errors = Validation::validate_api_key($api_key);
    if (! empty($validation_errors)) {
        return new WP_REST_Response( $validation_errors );
    }

    $update = isset($post['update']) ? $post['update'] : '';

    if ($update == 'true') {
        add_filter( 'auto_update_theme', '__return_true' );
        return 'Auto Update Theme Enabled';
    } else {
        add_filter( 'auto_update_theme', '__return_false' );
        return 'Auto Update Theme Disabled';
    }
}


/**
 * Disable all comments
 * * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
 */
function bw_post_disable_comments(WP_REST_Request $request) {
    $post = $request->get_params();
	$api_key = $post['api_key'];
    $validation_errors = Validation::validate_api_key($api_key);
    if (! empty($validation_errors)) {
        return new WP_REST_Response( $validation_errors );
    }

	// Turn off pings
	if( '' != get_option( 'default_ping_status' ) ) {
		update_option( 'default_ping_status', '' );
	}

	// Turn off comments
	if( '' != get_option( 'default_comment_status' ) ) {
		update_option( 'default_comment_status', '' );
    }
    
    // switched off all posts even media
	add_filter( 'comments_open', '__return_false', 10, 2 );
	return 'Comments Disabled';
}

/**
 * Get comments status
 * * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
 */
function bw_get_status_comments(WP_REST_Request $request) {
    $get = $request->get_params();

    $ret = [];
    $ret[] = 'Default ping status: ' . get_option( 'default_ping_status' );
    $ret[] = 'Default comment status: ' . get_option( 'default_comment_status' );

	return new WP_REST_Response( $ret );
}


/**
 * Create new user account
 * * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
 */
 
function bw_post_create_user(WP_REST_Request $request) 
{
    $post = $request->get_params();
	$api_key = $post['api_key'];
    $validation_errors = Validation::validate_api_key($api_key);
    if (! empty($validation_errors)) {
        return new WP_REST_Response( $validation_errors );
    }

    // Validation for inputs
    if( isset($post['user_login']) &&
        isset($post['user_pass']) &&
        isset($post['user_email']) &&
        isset($post['role'])) {        
    } else {
        return new WP_REST_Response('Missing Parameters');
    }

    $user = [
        'user_login' => $post['user_login'],
        'user_pass' => $post['user_pass'],
        'user_email' => $post['user_email'],
        'role' => $post['role']
    ];

    $user_id = wp_insert_user($user);

    if(is_wp_error($user_id)){
        $msg = $user_id->get_error_message();
    } else {
        $msg = "Successfully inserted user ID: " . $user_id;
    }

    return $msg;
}


/**
 * Updates user account
 * * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
 */
 
function bw_post_update_user(WP_REST_Request $request) 
{
    $post = $request->get_params();
	$api_key = $post['api_key'];
    $validation_errors = Validation::validate_api_key($api_key);
    if (! empty($validation_errors)) {
        return new WP_REST_Response( $validation_errors );
    }

    // Validation for inputs
    if( isset($post['user_login']) &&
        ( isset($post['user_pass']) || isset($post['user_role']) )) {        
    } else {
        return new WP_REST_Response('Missing Parameters');
    }

	$msg = '';
    $user = get_user_by( 'login', $post['user_login']);
	
	if ( empty($user) ) {
        $msg = 'User does not exist';
    } else {
        $user_data_arr = $user->to_array();
        $user_data_arr['user_pass'] = $post['user_pass'];
        $updated_user_data = wp_update_user($user_data_arr);
        
        if (is_wp_error($updated_user_data)) {
            $msg = $updated_user_data->get_error_message();
        } else {
            $msg =  'User profile updated.';
        } 
    }
	
    return $msg;
}



/**
 * Remove role from user
 * * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
 */
 
function bw_post_add_role_user(WP_REST_Request $request) 
{
    $post = $request->get_params();
	$api_key = $post['api_key'];
    $validation_errors = Validation::validate_api_key($api_key);
    if (! empty($validation_errors)) {
        return new WP_REST_Response( $validation_errors );
    }

    // Validation for inputs
    if( isset($post['user_login']) && isset($post['user_role']) ) {        
    } else {
        return new WP_REST_Response('Missing Parameters');
    }

	$msg = '';
    $user = get_user_by( 'login', $post['user_login']);
	
	if ( empty($user) ) {
        $msg = 'User does not exist';
    } else {
        $user->add_role($post['user_role']);
        $msg = 'Success - Role added to user.';
    }
	
    return $msg;
}



/**
 * Updates user account
 * * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
 */
 
function bw_post_remove_role_user(WP_REST_Request $request) 
{
    $post = $request->get_params();
	$api_key = $post['api_key'];
    $validation_errors = Validation::validate_api_key($api_key);
    if (! empty($validation_errors)) {
        return new WP_REST_Response( $validation_errors );
    }

    // Validation for inputs
    if( isset($post['user_login']) && isset($post['user_role']) ) {        
    } else {
        return new WP_REST_Response('Missing Parameters');
    }

	$msg = '';
    $user = get_user_by( 'login', $post['user_login']);
	
	if ( empty($user) ) {
        $msg = 'User does not exist';
    } else {
        $user->remove_role($post['user_role']);
        $msg = 'Success - Role removed from user.';
    }
	
    return $msg;
}


/**
 * Get available plugin versions
 * * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
 */
function bw_check_plugin_updates(WP_REST_Request $request) {

    $plugins_versions = get_option('_site_transient_update_plugins');

    return new WP_REST_Response($plugins_versions);
}



/**
 * Get available plugin versions
 * * 
 * @param WP_REST_Request $request
 * @return WP_REST_Response $response 
 */
function bw_check_core_updates(WP_REST_Request $request) {

    $plugins_versions = get_option('_site_transient_update_core');

    return new WP_REST_Response($plugins_versions);
}



