<?php

class Wiaas_Admin_Organization {

    public static function init() {
        // role switcher for organization
        add_action( 'admin_bar_menu', array( __CLASS__, 'add_role_switcher_menu' ), 10, 2 );

        // change user role if requested
        add_action('admin_init', array(__CLASS__, 'maybe_change_user_role'));

        add_filter('manage_users_columns', array(__CLASS__, 'manage_users_table_columns'));
        add_filter('views_users', array(__CLASS__, 'hide_users_table_list_navigation'));

        add_filter('get_role_list', array(__CLASS__, 'get_role_list_for_user'), 10, 2);

        // hide woocommerce meta fields form customer user profile
        add_filter('woocommerce_customer_meta_fields', array(__CLASS__, 'hide_woocommerce_customer_fields'));

        // save related customers when organization form data has been saved by acf
	  //  add_action('acf/save_post', array(__CLASS__, 'maybe_save_related_customers'), 999);

	    // load related customers for organization form
	  //  add_filter('acf/load_value/name=_wiaas_organization_customers', array(__CLASS__, 'load_related_customer_organizations'), 10, 3);

	    // retrieve only customer organizations as options to link to commercial lead
	//    add_filter('acf/fields/taxonomy/query/name=_wiaas_organization_customers', array(__CLASS__, 'filter_customer_organizations'));
    }

    public static function hide_woocommerce_customer_fields() {
        return array();
    }

    public static function hide_users_table_list_navigation() {
        return array();
    }

	/**
	 * Retrieve only customer organization as options to link customers to commercial lead
	 *
	 * @param $args
	 *
	 * @return array
	 */
    public static function filter_customer_organizations($args) {

		$args['meta_key'] = '_wiaas_organization_roles';
	    $args['meta_value'] = 'customer';
	    $args['meta_compare'] = 'LIKE';

    	return $args;
    }

	/**
	 * Saves related customers if organization new/edit form has been submited
	 * Customer ids are collected from posted data of linked customers acf field and saved
	 *
	 * @param string $id in format `term_{$organization_id}`
	 */
	public static function maybe_save_related_customers($id) {
		if ($_POST['taxonomy'] === Wiaas_User_Organization::TAXONOMY_NAME && ! empty($_POST['acf'])) {

			$field = get_field_object('_wiaas_organization_customers', $id);
			//get organization id
			$id = absint(str_replace('term_', '', $id));

			if (!$id) {
				return;
			}

			$customer_organization_ids = $_POST['acf'][$field['key']];

			$customer_organization_ids = is_array($customer_organization_ids) ?
				wp_parse_id_list($customer_organization_ids) :
				array();

			Wiaas_Shop::set_shop_customers($id, $customer_organization_ids);
		}
	}

	/**
	 * Loads related customers for linked customers acf field on organization edit form
	 *
	 * @param array $value
	 * @param string $id in format `term_{$organization_id}`
	 * @param array $field acf field details
	 *
	 * @return array
	 */
	public static function load_related_customer_organizations($value, $id, $field) {
		//get organization id
		$id = absint(str_replace('term_', '', $id));

		$customers =  wp_list_pluck(
			Wiaas_Shop::get_shop_customers($id),
			'customer_id');

		return $customers;
	}

	/**
	 * Render user organization roles as available user roles on user list
	 * @param $role_list
	 * @param $user
	 *
	 * @return mixed
	 */
    public static function get_role_list_for_user($role_list, $user) {
        $organization_id = wiaas_get_user_organization_id($user->ID);

        if (! empty($organization_id)) {
            $organization_roles = wiaas_get_organization_roles($organization_id);

            foreach ($organization_roles as $organization_role) {
                $role_list[$organization_role] = translate_user_role( wp_roles()->role_names[ $organization_role ] );
            }

            if (! empty($organization_role)) {
                unset($role_list['none']);
            }
        }

        return $role_list;
    }

	/**
	 * Customize columns for users table list view
	 *
	 * @param array $defaults
	 *
	 * @return array
	 */
    public static function manage_users_table_columns( $defaults = array() ) {

        $defaults['role'] = __('Roles', 'wiaas');

        unset($defaults['posts']);

        return $defaults;
    }

    /**
     * Adds organization roles switcher menu to admin bar
     *
     * @param $admin_bar
     */
    public static function add_role_switcher_menu($admin_bar) {
        if (is_super_admin()) {
            $roles = array( 'administrator' );
        } else {
            $organization_id = wiaas_get_current_user_organization_id();
            $roles = wiaas_get_organization_roles($organization_id);
        }

        $user = wp_get_current_user();
        $current_role  = $user->roles[0];

        // Add menu item.
        $admin_bar->add_menu( array(
            'id'     => 'wiaas-view-as',
            'parent' => 'top-secondary',
            'title'  => '<span>' .
                __( 'View as:', 'wiaas' ) .
                '</span>' .
                '<span style="margin-left: 6px; font-weight: bold;">'.
                __(translate_user_role( wp_roles()->role_names[ $current_role ] ), 'wiaas') .
                '</span>' .
                '<i style="float: right;" class="ab-icon dashicons dashicons-arrow-down"></i>',
            'href'   => false,
            'meta'   => array(
                'title'    => __( 'View As', 'wiaas' ),
                'tabindex' => '0',
            ),
        ) );

        foreach ($roles as $role) {
            $role_name = translate_user_role( wp_roles()->role_names[ $role ] );

            if ($role === $current_role) {
                // highlight current role
                $title = '<span class="ab-label">' . __( $role_name, 'wiaas' ) . '</span>';

                $url = false;

            } else if ($role === 'customer') {
                // set external link for customer role
                $title = '<span>' . __( $role_name, 'wiaas' ) . '</span>';
                $title .= '<span class="ab-icon dashicons dashicons-external"></span>';

                $url = WIAAS_CUSTOMER_INTERFACE;

                $target = '_blank';

            } else {
                $title = '<span>' . __( $role_name, 'wiaas' ) . '</span>';

                $url = wp_nonce_url(admin_url(), 'wiaas-set-role', 'wiaas-set-role-nonce');
                $url = add_query_arg( 'wiaas-role', $role, $url );

                $target = '_parent';
            }

            $admin_bar->add_menu( array(
                'id'     => 'wiaas_'.$role,
                'parent' => 'wiaas-view-as',
                'title'  => $title,
                'href'   => $url,
                'meta'   => array(
                    'title'    => __( $role_name, 'wiaas' ),
                    'target' => $target
                ),
            ) );
        }
    }


    /**
     *
     * Process organization role switch request if needed
     *
     */
    public static function maybe_change_user_role() {
        if (! empty($_GET['wiaas-set-role-nonce']) && ! empty($_GET['wiaas-role'])) {
            if (wp_verify_nonce($_GET['wiaas-set-role-nonce'], 'wiaas-set-role')) {
                $role_name = sanitize_key($_GET['wiaas-role']);

                $role = wp_roles()->get_role($role_name);

                if (! empty($role) && $role_name !== 'customer') {
                    // get current user
                    $current_user = wp_get_current_user();

                    update_user_meta($current_user->ID, '_wiaas_current_user_admin_role', $role->name);

                    // switch user role
                    $current_user->set_role($role->name);
                }
            }

            wp_safe_redirect( admin_url('index.php') );
            exit;
        }
    }
}

Wiaas_Admin_Organization::init();
