<?php

/**
 * Retrieves name for provided organization_id
 * @param int $organization_id
 *
 * @return string|null
 */
function wiaas_get_organization_name($organization_id) {
    $term = get_term($organization_id);

    if ($term instanceof WP_Term) {
        return $term->name;
    }

    return null;
}

/**
 * Retrieve array of organization role names
 *
 * @param int $organization_id
 *
 * @return array Array of organization roles
 */
function wiaas_get_organization_roles($organization_id) {
    $roles = get_term_meta($organization_id, '_wiaas_organization_roles', true);

    return empty($roles) ? array() : $roles;
}

/**
 * @param int $organization_id
 * @param array $roles
 */
function wiaas_set_organization_roles($organization_id, $roles) {
    update_term_meta($organization_id, '_wiaas_organization_roles', $roles);
}

/**
 * Retrieves list of organizations with provided role in [ 'id' => 'name'] format
 * @param string $role
 *
 * @return array
 */
function wiaas_get_organizations_with_role($role) {
    $terms = get_terms(array(
        'taxonomy' => Wiaas_User_Organization::TAXONOMY_NAME,
        'meta_key' => '_wiaas_organization_roles',
        'meta_value' => $role,
        'fields' => 'id=>name',
        'meta_compare' => 'LIKE',
        'hide_empty' => false
    ));

    return is_array($terms) ? $terms : array();
}

/**
 * Retrieves list of commercial lead organizations in [ 'id' => 'name' ] format
 *
 * @return array
 */
function wiaas_get_commercial_leads() {
    return wiaas_get_organizations_with_role('commercial_lead');
}

/**
 * Retrieves list of customer organizations in [ 'id' => 'name'] format
 *
 * @return array
 */
function wiaas_get_customers() {
    return wiaas_get_organizations_with_role('customer');
}

/**
 * Retrieves list of supplier organizations in [ 'id' => 'name'] format
 *
 * @return array
 */
function wiaas_get_suppliers() {
    return wiaas_get_organizations_with_role('supplier');
}

/**
 * Retrieves id of organization for provided user_id
 *
 * @param int $user_id
 *
 * @return int|null
 */
function wiaas_get_user_organization_id($user_id) {
    $organization_id = get_user_meta($user_id, '_wiaas_organization_id', true);

    return empty($organization_id) ? null : (int) $organization_id;
}

/**
 * Retrieves id of current user organization
 *
 * @return int|null
 */
function wiaas_get_current_user_organization_id() {
    return wiaas_get_user_organization_id(get_current_user_id());
}