<?php

/**
 * Handles user authentication for wiaas
 *
 * User roles are inherited from organization
 *
 * Class Wiaas_Authentication
 */
class Wiaas_Authentication {

    const SUPER_ADMIN_USER_ID = 1;

    public static function init() {
        // authenticate current user
      //  add_action('determine_current_user', array(__CLASS__, 'authenticate_current_user'), 999);

        // authenticates user on login
     //   add_filter( 'authenticate', array( __CLASS__, 'authenticate_user_on_login' ), 999, 3);

        // retrieve preferred user role for user
       add_filter('get_user_metadata', array(__CLASS__, 'maybe_filter_user_roles'), 10, 3);

        // redirect to dashboard after login
    //    add_filter( 'login_redirect', array( __CLASS__, 'login_redirect' ) );
    }

    /**
     * Redirect admin user to dashboard
     *
     * @return string
     */
    public static function login_redirect() {
        return  admin_url('index.php') ;
    }


    /**
     * Authenticate current user based on roles assigned to organization
     *
     *  User role will be determined in `maybe_filter_user_roles` based on his organization roles
     *
     * If this is REST API request user will be only authenticated with customer role if his organization has
     * customer role assigned to it.
     *
     * If this is backend request user will be authenticated with previously selected or first available role
     * from his organization roles.
     *
     * @param int|false $user_id
     * @return int|false|WP_Error
     */
    public static function authenticate_current_user($user_id) {
        // do nothing if user not authenticated, user is super admin or this is REST API request
        if (! $user_id || $user_id === self::SUPER_ADMIN_USER_ID) {
            return $user_id;
        }

	    $user = new WP_User($user_id);

	    if (empty($user->roles)) {
		    return new WP_Error('wiaas_authentication_error', 'No permissions!');
	    }

        return $user_id;
    }

    /**
     * Authenticate wiaas user on login based on roles assigned to organization
     *
     * User role will be determined in `maybe_filter_user_roles` based on his organization roles
     *
     * If this is REST API login request user will be only authenticated with customer role if his organization his
     * customer role assigned to it.
     *
     * If this is backend login request user will be authenticated with previously selected or first available role
     * from his organization roles.
     *
     * @param WP_User $user
     * @return WP_User|WP_Error
     */
    public static function authenticate_user_on_login($user) {
        // do nothing if there is an error already,
        // user is super admin
        if (is_wp_error($user) || $user->ID === 1) {
            return $user;
        }

       if (empty($user->roles)) {
            return new WP_Error('wiaas_authentication_error', 'No permissions!');
       }

        return $user;
    }


    /**
     *
     * Override default user roles with only his organization roles.
     *
     * If this is REST API request retrieve customer role if organization has that role.
     *
     * If this is backend request retrieve previously selected role or first available organization role with
     * backend access.
     *
     * @param $null
     * @param int $user_id
     * @param string $meta_key
     * @return array|null
     */
    public static function maybe_filter_user_roles($null, $user_id, $meta_key) {

        global $wpdb;

        if ($user_id !== 0 && $user_id !== self::SUPER_ADMIN_USER_ID && $meta_key === $wpdb->get_blog_prefix() . 'capabilities') {

        	return array( array( 'customer' => true ) );

	        // import organization functions (during user authentication it is not yet loaded)
	        require_once dirname( __FILE__ ) . '/user/wiaas-organization-functions.php';

	        // get user organization
	        $organization_id = wiaas_get_user_organization_id($user_id);

	        // validate if user has organization
	        if ( empty( $organization_id) ) {
		        return array();
	        }

	        // get organization roles
	        $roles = wiaas_get_organization_roles($organization_id);

	        // if organization has no roles assigned to it user will have no roles
	        if ( empty($roles) ) {
		        return array();
	        }

	        /**
	         * REST API access
	         */

	        // for REST API access allow only customer role for user
            if ( $is_rest_api = strpos($_SERVER['REQUEST_URI'], rest_get_url_prefix()) ) {
                return in_array('customer', $roles) ? array( array( 'customer' => true ) ) : array();
            }

	        /**
	         * BACKEND ACCESS
	         */

	        // remove customer role
	        $roles = array_diff($roles, array( 'customer'));

	        // not available backend roles for user
            if ( empty($roles) ) {
                return array();
            }

            // retrieve selected role for user
            $role =  get_user_meta($user_id, '_wiaas_current_user_admin_role', true);

            // if user has no selected role, selected role in invalid (deleted) or organization has no selected role
            // assign first available role to user
	        if ( empty($role) ||
                ! wp_roles()->is_role($role) ||
                ! in_array($role, $roles) ) {

		        // pick first role
		        $role = $roles[0];
		        update_user_meta($user_id, '_wiaas_current_user_admin_role', $role);
	        }

            return array( array ( "$role" => true ));
        }

        return null;
    }
}

Wiaas_Authentication::init();
